/* NutriDMS, Enterprise Sign-in Flow */
const { useState: useSIState, useEffect: useSIEffect, useRef: useSIRef } = React;
const _SiCtx = { role:"super-admin", page:"signin", setPage:()=>{}, lang:"en", setLang:()=>{}, openCmd:()=>{}, openNotif:()=>{} };

const SI_STEPS = [
  { id: "login", label: "Sign in" },
  { id: "forgot", label: "Reset" },
  { id: "otp", label: "OTP" },
  { id: "newpass", label: "New password" },
  { id: "setup", label: "Account setup" },
  { id: "loading", label: "Loading" },
];

/* ─── Toast ─── */
function SIToast({ toast, onClose }) {
  if (!toast) return null;
  const icMap = { error: "alert-triangle", success: "check-circle-2", info: "info" };
  return (
    <div className={`si-toast ${toast.kind}`}>
      <div className="ic"><Icon name={icMap[toast.kind] || "info"} size={16} stroke={2.4}/></div>
      <div className="body"><strong>{toast.title}</strong>{toast.msg}</div>
      <button className="x" onClick={onClose} aria-label="Dismiss"><Icon name="x" size={14} stroke={2.4}/></button>
    </div>
  );
}

/* ─── Brand Panel (dashboard hero + carousel) ─── */
const SI_SLIDES = [
  { h: "Compliance friendly enterprise nutrition platform.",
    p: "Sign in to your workspace, or talk to your account manager about a tailored rollout for our organization." },
  { h: "Validation built into every workflow.",
    p: "Loraa AI checks nutrition, allergens, and claims as your team works, so nothing ships wrong." },
  { h: "Audit ready by design.",
    p: "Every change is logged and tamper-evident, giving your compliance team a defensible trail." },
];

function BrandPanel() {
  const [i, setI] = useSIState(0);
  useSIEffect(() => {
    const id = setInterval(() => setI(v => (v + 1) % SI_SLIDES.length), 7000);
    return () => clearInterval(id);
  }, []);
  const prev = () => setI(v => (v - 1 + SI_SLIDES.length) % SI_SLIDES.length);
  const next = () => setI(v => (v + 1) % SI_SLIDES.length);
  const s = SI_SLIDES[i];
  return (
    <aside className="si-brand">
      <div className="si-brand-top" style={{ width: 528, height: 43 }}>
        <a href="Landing.html" className="si-brand-logo"><NutriHoriz height={44} forceTheme="dark"/></a>
        <span className="si-ent-pill">Enterprise</span>
      </div>
      <div className="si-brand-card">
        <h2 key={i}>{s.h}</h2>
        <p key={"p"+i}>{s.p}</p>
        <div className="si-carousel">
          <div className="si-dots">
            {SI_SLIDES.map((_, k) => (
              <button key={k} className={k === i ? "on" : ""} onClick={() => setI(k)} aria-label={`Slide ${k+1}`}/>
            ))}
          </div>
          <div className="si-arrows">
            <button onClick={prev} aria-label="Previous"><Icon name="arrow-left" size={16} stroke={2.4}/></button>
            <button onClick={next} aria-label="Next"><Icon name="arrow-right" size={16} stroke={2.4}/></button>
          </div>
        </div>
      </div>
      <img src="assets/signin-dashboard.png" alt="NutriDMS analytics dashboard" className="si-dash" style={{ left: -17, top: -36, position: "absolute", width: 610 }}/>
    </aside>
  );
}

/* ─── Step picker (demo aid) ─── */
function StepPickerDev({ step, setStep }) {
  return (
    <div className="si-stepper-dev" role="navigation">
      <span className="label">Demo:</span>
      {SI_STEPS.map(s => (
        <button key={s.id} className={step === s.id ? "on" : ""} onClick={() => setStep(s.id)}>{s.label}</button>
      ))}
    </div>
  );
}

/* ─── Login ─── */
function LoginScreen({ go, toast, setToast }) {
  const [email, setEmail] = useSIState("");
  const [pw, setPw] = useSIState("");
  const [showPw, setShowPw] = useSIState(false);
  const [emailErr, setEmailErr] = useSIState(false);
  const [pwErr, setPwErr] = useSIState(false);

  const submit = (e) => {
    e.preventDefault();
    const validEmail = /^\S+@\S+\.\S+$/.test(email);
    setEmailErr(!validEmail);
    setPwErr(pw.length < 1);
    if (!validEmail || pw.length < 1) {
      setToast({ kind: "error", title: "Invalid credentials", msg: "The email or password you entered is incorrect. Please try again." });
      return;
    }
    setToast(null);
    go("loading", { next: "dashboard" });
  };

  return (
    <div className="si-card">
      <h1 className="si-title">Sign in</h1>
      <p className="si-sub">Welcome back. Please sign in to your enterprise workspace.</p>
      <form className="si-form" onSubmit={submit} noValidate>
        <div className="si-field">
          <label>Work email <span className="req">*</span></label>
          <div className={`si-input-wrap ${emailErr ? "error":""}`}>
            <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@yourcompany.com" autoComplete="email"/>
          </div>
          {emailErr && <div className="err-text"><Icon name="alert-circle" size={12} stroke={2.4}/> Please enter a valid email.</div>}
        </div>
        <div className="si-field">
          <label>Password <span className="req">*</span></label>
          <div className={`si-input-wrap ${pwErr ? "error":""}`}>
            <input type={showPw ? "text" : "password"} value={pw} onChange={e=>setPw(e.target.value)} placeholder="Enter your password" autoComplete="current-password"/>
            <button type="button" className="toggle-pass" onClick={()=>setShowPw(!showPw)} aria-label={showPw?"Hide":"Show"}>
              <Icon name={showPw ? "eye-off" : "eye"} size={16} stroke={2.2}/>
            </button>
          </div>
        </div>
        <div className="si-row" style={{marginTop:-4, marginBottom:8}}>
          <label className="si-checkbox" style={{padding:0}}>
            <input type="checkbox"/>
            <span className="box"><Icon name="check" size={11} stroke={3.2}/></span>
            <span>Keep me signed in</span>
          </label>
          <a href="#" className="si-link" onClick={(e)=>{e.preventDefault(); go("forgot");}}>Forgot password?</a>
        </div>
        <button type="submit" className="btn primary si-cta" disabled={!email || !pw}><Icon name="log-in" size={15} stroke={2.4}/> Sign in</button>
      </form>

      <div className="si-divider">or continue with</div>
      <div className="si-sso-row">
        <button className="si-sso-btn" data-tip="Single Sign-On (SSO) lets users access multiple apps or websites with one secure login, instead of using separate usernames and passwords for each platform."><Icon name="key-round" size={15} stroke={2.2}/> SSO</button>
        <button className="si-sso-btn"><svg width="16" height="16" viewBox="0 0 48 48" aria-hidden="true"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.6l6.8-6.8C35.6 2.4 30.2 0 24 0 14.6 0 6.4 5.4 2.5 13.3l7.9 6.2C12.3 13.4 17.6 9.5 24 9.5z"/><path fill="#4285F4" d="M46.1 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.4c-.5 2.9-2.2 5.3-4.6 6.9l7.1 5.5c4.1-3.8 6.5-9.4 6.5-16z"/><path fill="#FBBC05" d="M10.4 28.5c-.5-1.4-.8-2.9-.8-4.5s.3-3.1.8-4.5l-7.9-6.2C.9 16.5 0 20.1 0 24s.9 7.5 2.5 10.7l7.9-6.2z"/><path fill="#34A853" d="M24 48c6.2 0 11.4-2 15.2-5.6l-7.1-5.5c-2 1.3-4.5 2.1-8.1 2.1-6.4 0-11.7-3.9-13.6-9.5l-7.9 6.2C6.4 42.6 14.6 48 24 48z"/></svg> Google</button>
        <button className="si-sso-btn"><svg width="15" height="15" viewBox="0 0 23 23" aria-hidden="true"><path fill="#F25022" d="M0 0h11v11H0z"/><path fill="#7FBA00" d="M12 0h11v11H12z"/><path fill="#00A4EF" d="M0 12h11v11H0z"/><path fill="#FFB900" d="M12 12h11v11H12z"/></svg> Microsoft</button>
      </div>
      <div className="si-footnote">
        New to NutriDMS? <a href="screens/register.html">Start a free 7-day trial</a> or <a href="book-demo.html">book an enterprise demo</a>.
      </div>
    </div>
  );
}

/* ─── Forgot (reset password, send OTP) ─── */
function ForgotScreen({ go, setToast }) {
  const [email, setEmail] = useSIState("");
  const [err, setErr] = useSIState(false);

  const submit = (e) => {
    e.preventDefault();
    if (email.toLowerCase().includes("notfound")) {
      setErr(true);
      setToast({ kind: "error", title: "Email does not exist", msg: "Confirm if your email is correct." });
      return;
    }
    setToast({ kind: "success", title: "OTP sent", msg: "Check your email for a 4-digit one-time password." });
    go("otp", { email });
  };

  return (
    <div className="si-card">
      <h1 className="si-title">Reset password</h1>
      <p className="si-sub">Enter your email to regain access to your account. We'll send a one-time password to verify it's you.</p>
      <form className="si-form" onSubmit={submit} noValidate>
        <div className="si-field">
          <label>Email <span className="req">*</span></label>
          <div className={`si-input-wrap ${err ? "error":""}`}>
            <input type="email" value={email} onChange={e=>{setEmail(e.target.value); setErr(false);}} placeholder="you@yourcompany.com" autoComplete="email"/>
          </div>
          {err && <div className="err-text"><Icon name="alert-circle" size={12} stroke={2.4}/> No account found for that email.</div>}
        </div>
        <button type="submit" className="btn primary si-cta" disabled={!email}><Icon name="send" size={15} stroke={2.4}/> Send OTP</button>
      </form>
      <div className="si-footnote">
        Remembered it? <a href="#" onClick={(e)=>{e.preventDefault(); go("login");}}>Back to sign in</a>
      </div>
    </div>
  );
}

/* ─── OTP entry ─── */
function OtpScreen({ go, setToast, ctx }) {
  const [digits, setDigits] = useSIState(["", "", "", ""]);
  const [err, setErr] = useSIState(false);
  const refs = [useSIRef(), useSIRef(), useSIRef(), useSIRef()];

  useSIEffect(() => { refs[0].current && refs[0].current.focus(); }, []);

  const setDigit = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const nd = [...digits]; nd[i] = v; setDigits(nd); setErr(false);
    if (v && i < 3) refs[i+1].current && refs[i+1].current.focus();
    if (!v && i > 0) {/* allow backspace */ }
    if (nd.every(d => d) && i === 3) {
      // simulate validate
      setTimeout(() => {
        const code = nd.join("");
        if (code === "1111") {
          setErr(true);
          setToast({ kind: "error", title: "OTP is incorrect", msg: "Your may have not received it or expired." });
        } else {
          setToast(null);
          go("newpass");
        }
      }, 150);
    }
  };

  const onKey = (i, e) => {
    if (e.key === "Backspace" && !digits[i] && i > 0) refs[i-1].current && refs[i-1].current.focus();
  };

  const resend = (e) => { e.preventDefault(); setToast({ kind: "success", title: "OTP sent", msg: "Check your email for a new code." }); setDigits(["","","",""]); refs[0].current && refs[0].current.focus(); };

  return (
    <div className="si-card">
      <h1 className="si-title">Enter OTP</h1>
      <p className="si-sub">To verify your email, we've sent a one-time password to {ctx.email ? <strong>{ctx.email}</strong> : <strong>your work email</strong>}.</p>
      <div className={`si-otp-row ${err ? "error":""}`}>
        {digits.map((d, i) => (
          <input key={i} ref={refs[i]} inputMode="numeric" maxLength={1} value={d} onChange={e=>setDigit(i, e.target.value)} onKeyDown={e=>onKey(i,e)} aria-label={`Digit ${i+1}`}/>
        ))}
      </div>
      <div className="si-otp-resend">Didn't receive code? <a href="#" onClick={resend}>Resend</a></div>
      <button className="btn primary si-cta" style={{marginTop:24}} disabled={digits.some(d=>!d)} onClick={()=>{ if (digits.join("") === "1111") { setErr(true); setToast({kind:"error",title:"OTP is incorrect", msg:"Your may have not received it or expired."}); } else { setToast(null); go("newpass"); }}}><Icon name="shield-check" size={15} stroke={2.4}/> Confirm</button>
    </div>
  );
}

/* ─── Set New Password ─── */
function passRules(pw) {
  return [
    { id: "len", t: "At least 8 characters long", ok: pw.length >= 8 },
    { id: "case", t: "Contains at least one capital letter", ok: /[A-Z]/.test(pw) },
    { id: "num", t: "Contains at least one number", ok: /\d/.test(pw) },
    { id: "sym", t: "Contains at least one symbol", ok: /[^A-Za-z0-9]/.test(pw) },
  ];
}

function NewPasswordScreen({ go, setToast }) {
  const [pw, setPw] = useSIState("");
  const [pw2, setPw2] = useSIState("");
  const [showPw, setShowPw] = useSIState(false);
  const [signOutAll, setSignOutAll] = useSIState(true);
  const [mismatch, setMismatch] = useSIState(false);

  const rules = passRules(pw);
  const allOk = rules.every(r => r.ok);
  const valid = allOk && pw === pw2 && pw2.length > 0;

  const submit = (e) => {
    e.preventDefault();
    if (!allOk) return;
    if (pw !== pw2) {
      setMismatch(true);
      setToast({ kind: "error", title: "Password mismatch", msg: "Your passwords don't match. Please re-enter and try again." });
      return;
    }
    setToast({ kind: "success", title: "Password reset", msg: "Your password was successfully changed." });
    go("loading", { next: "dashboard", message: "Signing you in", sub: "Your password was successfully changed. Signing you in, please wait a moment." });
  };

  return (
    <div className="si-card">
      <h1 className="si-title">Set new password</h1>
      <p className="si-sub">Create a new password you'll remember.</p>
      <form className="si-form" onSubmit={submit} noValidate>
        <div className="si-field">
          <label>New password <span className="req">*</span></label>
          <div className="si-input-wrap">
            <input type={showPw?"text":"password"} value={pw} onChange={e=>{setPw(e.target.value); setMismatch(false);}} placeholder="Enter new password" autoComplete="new-password"/>
            <button type="button" className="toggle-pass" onClick={()=>setShowPw(!showPw)} aria-label="Toggle"><Icon name={showPw?"eye-off":"eye"} size={16} stroke={2.2}/></button>
          </div>
        </div>
        <div className="si-field">
          <label>Confirm password <span className="req">*</span></label>
          <div className={`si-input-wrap ${mismatch ? "error":""}`}>
            <input type={showPw?"text":"password"} value={pw2} onChange={e=>{setPw2(e.target.value); setMismatch(false);}} placeholder="Re-enter new password" autoComplete="new-password"/>
          </div>
          {mismatch && <div className="err-text"><Icon name="alert-circle" size={12} stroke={2.4}/> Passwords don't match.</div>}
        </div>

        <label className="si-checkbox" style={{marginTop:0}}>
          <input type="checkbox" checked={signOutAll} onChange={e=>setSignOutAll(e.target.checked)}/>
          <span className="box"><Icon name="check" size={11} stroke={3.2}/></span>
          <span>Sign out of all other devices</span>
        </label>

        <div className="si-rules">
          {rules.map(r => (
            <div key={r.id} className={`r ${r.ok ? "ok":""}`}>
              <span className="ic"><Icon name="check" size={10} stroke={3.2}/></span>
              {r.t}
            </div>
          ))}
        </div>
        <button type="submit" className="btn primary si-cta" disabled={!valid}><Icon name="key-round" size={15} stroke={2.4}/> Reset password</button>
      </form>
    </div>
  );
}

/* ─── Account Setup ─── */
function SetupScreen({ go, setToast }) {
  const [data, setData] = useSIState({ first: "", last: "", company: "", role: "Compliance Lead", agreed: true });
  const set = (k, v) => setData(d => ({...d, [k]: v}));
  const valid = data.first && data.last && data.company && data.agreed;
  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    setToast({ kind: "success", title: "Account ready", msg: "Setting up your workspace…" });
    go("loading", { next: "dashboard", message: "Setting up your dashboard", sub: "Your nutrition workspace is being prepared. Signing you in shortly." });
  };
  return (
    <div className="si-card">
      <h1 className="si-title">Account setup</h1>
      <p className="si-sub">Add the details we use to personalize your workspace and send you the right updates.</p>
      <form className="si-form" onSubmit={submit} noValidate>
        <div className="si-field">
          <label>First name <span className="req">*</span></label>
          <div className="si-input-wrap"><input value={data.first} onChange={e=>set("first", e.target.value)} placeholder="Sarah"/></div>
        </div>
        <div className="si-field">
          <label>Last name <span className="req">*</span></label>
          <div className="si-input-wrap"><input value={data.last} onChange={e=>set("last", e.target.value)} placeholder="Chen"/></div>
        </div>
        <div className="si-field">
          <label>Business name <span className="req">*</span></label>
          <div className="si-input-wrap"><input value={data.company} onChange={e=>set("company", e.target.value)} placeholder="Acme Foods"/></div>
        </div>
        <div className="si-field">
          <label>Role</label>
          <div className="si-input-wrap">
            <select value={data.role} onChange={e=>set("role", e.target.value)}>
              <option>Compliance Lead</option><option>QA Reviewer</option><option>Dietitian</option>
              <option>Recipe Contributor</option><option>Media Contributor</option>
              <option>Manager</option><option>Enterprise Admin</option>
            </select>
          </div>
        </div>
        <label className="si-checkbox">
          <input type="checkbox" checked={data.agreed} onChange={e=>set("agreed", e.target.checked)}/>
          <span className="box"><Icon name="check" size={11} stroke={3.2}/></span>
          <span>I agree to the <a href="#" className="si-link">terms of service</a> and <a href="#" className="si-link">privacy policy</a>.</span>
        </label>
        <button type="submit" className="btn primary si-cta" disabled={!valid}><Icon name="check-check" size={15} stroke={2.4}/> Continue</button>
      </form>
    </div>
  );
}

/* ─── Loading screen ─── */
function LoadingScreen({ ctx }) {
  const [cancelled, setCancelled] = useSIState(false);
  useSIEffect(() => {
    if (cancelled) return;
    const id = setTimeout(() => { window.location.href = "index.html"; }, 2200);
    return () => clearTimeout(id);
  }, [cancelled]);
  return (
    <div className="si-loader si-success">
      <div className="si-success-icon">
        <span className="si-success-card back" />
        <span className="si-success-card front"><Icon name="check-circle-2" size={26} stroke={2.4}/></span>
      </div>
      <h2>You Are All Set!!</h2>
      <p>{cancelled ? "Redirect cancelled." : (ctx.sub || "Hold on we are currently redirecting you to your workspace…")}</p>
      {!cancelled && <div className="si-success-bar"><i /></div>}
      {!cancelled
        ? <button className="si-success-cancel" onClick={()=>setCancelled(true)}>Cancel</button>
        : <a href="index.html" className="btn primary si-cta" style={{marginTop:18,textDecoration:"none"}}><Icon name="arrow-right" size={15} stroke={2.4}/> Go to workspace</a>}
    </div>
  );
}

/* ─── Shell ─── */
function SignInShell() {
  const [step, setStep] = useSIState("login");
  const [ctx, setCtx] = useSIState({});
  const [toast, setToast] = useSIState(null);

  // Auto-dismiss toast after 6s
  useSIEffect(() => {
    if (!toast) return;
    const id = setTimeout(() => setToast(null), 6000);
    return () => clearTimeout(id);
  }, [toast]);

  const go = (next, payload = {}) => { setCtx(payload); setStep(next); setToast(t => (next === step ? t : t)); };
  const jump = (id) => { setStep(id); setCtx({}); setToast(null); };

  // Back-arrow target per step (rendered in the top bar, not the card).
  const BACK = { forgot: "login", otp: "forgot", newpass: "otp" };
  const backTo = BACK[step];

  const renderStep = () => {
    switch (step) {
      case "login":   return <LoginScreen go={go} toast={toast} setToast={setToast}/>;
      case "forgot":  return <ForgotScreen go={go} setToast={setToast}/>;
      case "otp":     return <OtpScreen go={go} setToast={setToast} ctx={ctx}/>;
      case "newpass": return <NewPasswordScreen go={go} setToast={setToast}/>;
      case "setup":   return <SetupScreen go={go} setToast={setToast}/>;
      case "loading": return <LoadingScreen ctx={ctx}/>;
      default: return null;
    }
  };

  return (
    <AppCtx.Provider value={_SiCtx}>
      <div className="si-wrap">
        <BrandPanel />
        <div className="si-form-wrap">
          <div className="si-form-top">
            <div className="si-locale-row">
              {backTo && (
                <button className="si-back-btn" data-tip="Back to previous screen" onClick={() => go(backTo)} aria-label="Back to previous screen">
                  <Icon name="arrow-left" size={18} stroke={2.6}/>
                </button>
              )}
              <LangSwitch />
              <button className="si-theme-btn" aria-label="Toggle theme"><Icon name="moon" size={16} stroke={2.2}/></button>
            </div>
            <a href="documentation.html#support" className="help-link"><Icon name="help-circle" size={19} stroke={2.2}/> Need Help?</a>
          </div>
          <div className="si-toast-stage">
            <SIToast toast={toast} onClose={()=>setToast(null)}/>
          </div>
          {renderStep()}
        </div>
      </div>
    </AppCtx.Provider>
  );
}

function SignInApp() {
  return <I18nProvider><SignInShell/></I18nProvider>;
}

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