// auth.jsx — sign-in / create-account page + account dropdown menu.
const { Icon: AuthIcon } = window;

// The seeded backend admin (see server/.env.example). Customers can use "Create account".
const DEMO_ACCOUNTS = [
  { role: "admin", email: "admin@megatech.local", password: "Admin123!", name: { en: "Administrator", ar: "المسؤول" } },
];

function LoginPage({ lang, t, mode, onModeChange, onAuthed, onBackToStore, onToggleLang, intent, toast }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [name, setName] = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [remember, setRemember] = React.useState(true);
  const [showPw, setShowPw] = React.useState(false);
  const [error, setError] = React.useState("");
  const [phoneFlow, setPhoneFlow] = React.useState(false);
  const isCreate = mode === "create";

  async function submit(e) {
    if (e) e.preventDefault();
    setError("");
    try {
      if (isCreate) {
        if (!name.trim() || !/^\S+@\S+\.\S+$/.test(email)) { setError(t.invalidCreds); return; }
        if (password.length < 6) { setError(t.invalidCreds); return; }
        if (password !== confirm) { setError(t.pwMismatch); return; }
        const res = await window.api.register({ name: name.trim(), email: email.trim().toLowerCase(), password });
        onAuthed(res);
        return;
      }
      const res = await window.api.login({ email: email.trim().toLowerCase(), password });
      onAuthed(res);
    } catch (err) {
      setError(err.message || t.invalidCreds);
    }
  }

  async function useDemo(acc) {
    setError("");
    try {
      const res = await window.api.login({ email: acc.email, password: acc.password });
      onAuthed(res);
    } catch (err) {
      setError(err.message || t.invalidCreds);
    }
  }

  function googleSignIn() {
    const cid = window.GOOGLE_CLIENT_ID;
    if (!cid || !(window.google && window.google.accounts && window.google.accounts.id)) {
      setError(lang === "en"
        ? "Google sign-in isn't configured yet (set GOOGLE_CLIENT_ID)."
        : "لم يتم إعداد تسجيل الدخول عبر Google بعد.");
      return;
    }
    try {
      window.google.accounts.id.initialize({
        client_id: cid,
        callback: async (resp) => {
          try { onAuthed(await window.api.google(resp.credential)); }
          catch (err) { setError(err.message); }
        },
      });
      window.google.accounts.id.prompt();
    } catch (err) { setError(err.message); }
  }

  return (
    <main className="authpage">
      <aside className="authpage__brand">
        <div className="authpage__brandtop">
          <span className="authpage__logo"><img src="assets/logo-megatech.png" alt="MegaTech" /></span>
          <button className="btn btn--onbrand-ghost btn--sm" onClick={onBackToStore}>
            <AuthIcon name="arrow-left" size={16} className="flip-x" />{t.backToStore}
          </button>
        </div>
        <div className="authpage__brandbody">
          <h2>{t.loginAside}</h2>
          <ul className="authpage__points">
            {[t.loginPt1, t.loginPt2, t.loginPt3].map((p, i) => (
              <li key={i}><span className="ic"><AuthIcon name="check-circle" size={20} /></span>{p}</li>
            ))}
          </ul>
        </div>
        <div className="authpage__brandfoot">{t.footerTag}</div>
      </aside>

      <section className="authpage__panel">
        <div className="authpage__formwrap">
          <div className="authpage__head">
            <span className="authpage__logo authpage__logo--sm"><img src="assets/logo-megatech.png" alt="MegaTech" /></span>
            <button className="langtoggle" onClick={onToggleLang}><AuthIcon name="globe" size={17} />{lang === "en" ? "العربية" : "EN"}</button>
          </div>

          {!phoneFlow && <h1 className="authpage__title">{isCreate ? t.createTitle : t.loginTitle}</h1>}
          {!phoneFlow && <p className="authpage__sub">{intent === "admin" && !isCreate ? t.needAdmin : isCreate ? t.createSub : t.loginSub}</p>}

          {phoneFlow ? (
            <PhoneAuthFlow lang={lang} t={t} onAuthed={onAuthed} onCancel={() => setPhoneFlow(false)} toast={toast} />
          ) : (
          <>
          {error && (
            <div className="authalert">
              <AuthIcon name="info" size={18} />{error}
            </div>
          )}

          <div className="authsso">
            <button type="button" className="googlebtn" onClick={googleSignIn}>
              <span className="googlebtn__g" aria-hidden="true">
                <svg viewBox="0 0 18 18" width="18" height="18">
                  <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-.81.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.58A9 9 0 0 0 .96 4.95l3.01 2.33C4.68 5.16 6.66 3.58 9 3.58z" />
                </svg>
              </span>
              {t.continueGoogle}
            </button>
            <button type="button" className="googlebtn" onClick={() => setPhoneFlow(true)}>
              <span className="googlebtn__g" style={{ color: "var(--brand-primary)" }} aria-hidden="true"><AuthIcon name="phone" size={18} /></span>
              {t.continuePhone}
            </button>
          </div>

          <div className="authdivider"><span>{t.orEmail}</span></div>

          <form onSubmit={submit} className="authform">
            {isCreate && (
              <Field label={t.nameLabel} req>
                <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder={lang === "en" ? "Karim Hassan" : "كريم حسن"} autoComplete="name" />
              </Field>
            )}
            <Field label={t.emailLabel} req>
              <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@business.com" autoComplete="email" />
            </Field>
            <Field label={t.passwordLabel} req>
              <div className="pwfield">
                <input className="input" type={showPw ? "text" : "password"} value={password} onChange={(e) => setPassword(e.target.value)} placeholder="••••••••" autoComplete={isCreate ? "new-password" : "current-password"} />
                <button type="button" className="pwfield__toggle" onClick={() => setShowPw(!showPw)} aria-label="Show password"><AuthIcon name="eye" size={18} /></button>
              </div>
            </Field>
            {isCreate && (
              <Field label={t.confirmLabel} req>
                <input className="input" type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="••••••••" autoComplete="new-password" />
              </Field>
            )}

            {!isCreate && (
              <div className="authform__row">
                <label className="checkline">
                  <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
                  <span className="checkbox"><AuthIcon name="check" size={13} /></span>
                  {t.rememberMe}
                </label>
                <button type="button" className="linkbtn" style={{ color: "var(--brand-primary)" }}>{t.forgot}</button>
              </div>
            )}

            <button type="submit" className="btn btn--primary btn--lg btn--block">
              <AuthIcon name="lock" size={18} />{isCreate ? t.createCta : t.signInCta}
            </button>
          </form>

          {!isCreate && (
            <>
              <div className="authdivider"><span>{t.orDivider}</span></div>
              <div className="demoaccts">
                {DEMO_ACCOUNTS.map((a) => (
                  <button key={a.email} className="demoacct" onClick={() => useDemo(a)}>
                    <span className={"demoacct__ic demoacct__ic--" + a.role}>
                      <AuthIcon name={a.role === "admin" ? "sliders" : "user"} size={18} />
                    </span>
                    <span className="demoacct__main">
                      <span className="demoacct__role">{a.role === "admin" ? t.roleAdmin : t.roleCustomer}</span>
                      <span className="demoacct__email num-tabular">{a.email}</span>
                    </span>
                    <AuthIcon name="arrow-right" size={18} className="flip-x demoacct__go" />
                  </button>
                ))}
              </div>
            </>
          )}

          <p className="authswitch">
            {isCreate ? t.haveAccount : t.noAccount}{" "}
            <button className="authswitch__link" onClick={() => { setError(""); onModeChange(isCreate ? "signin" : "create"); }}>
              {isCreate ? t.signInLink : t.createLink}
            </button>
          </p>
          </>
          )}
        </div>
      </section>
    </main>
  );
}

function AccountMenu({ auth, lang, t, onAdmin, onSignOut, onAction }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);
  const initials = (auth.name[lang] || auth.name.en).trim().split(/\s+/).map((w) => w[0]).slice(0, 2).join("");
  const isAdmin = auth.role === "admin";

  return (
    <div className="acctmenu" ref={ref}>
      <button className="acctbtn" onClick={() => setOpen(!open)}>
        <span className={"avatar" + (isAdmin ? " avatar--admin" : "")}>{initials}</span>
        <span className="acctbtn__name">{(auth.name[lang] || auth.name.en).split(/\s+/)[0]}</span>
        <AuthIcon name="chevron-down" size={16} />
      </button>
      {open && (
        <div className="acctpop">
          <div className="acctpop__head">
            <span className={"avatar" + (isAdmin ? " avatar--admin" : "")}>{initials}</span>
            <div className="acctpop__id">
              <div className="acctpop__name">{auth.name[lang] || auth.name.en}{isAdmin && <span className="badge badge--primary" style={{ marginInlineStart: 8 }}>{t.adminBadge}</span>}</div>
              <div className="acctpop__email num-tabular">{auth.email}</div>
            </div>
          </div>
          <div className="acctpop__items">
            {isAdmin && (
              <button className="acctpop__item" onClick={() => { setOpen(false); onAdmin(); }}>
                <AuthIcon name="sliders" size={18} />{t.adminConsole}
              </button>
            )}
            <button className="acctpop__item" onClick={() => { setOpen(false); onAction(t.myOrders); }}>
              <AuthIcon name="package" size={18} />{t.myOrders}
            </button>
            <button className="acctpop__item" onClick={() => { setOpen(false); onAction(t.savedItems); }}>
              <AuthIcon name="heart" size={18} />{t.savedItems}
            </button>
          </div>
          <div className="acctpop__foot">
            <button className="acctpop__item acctpop__item--danger" onClick={() => { setOpen(false); onSignOut(); }}>
              <AuthIcon name="log-out" size={18} />{t.signOut}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

const { Field } = window;

const AUTH_GOVS = {
  en: ["Cairo", "Giza", "Alexandria", "Dakahlia", "Sharqia", "Qalyubia", "Port Said", "Suez", "Other"],
  ar: ["القاهرة", "الجيزة", "الإسكندرية", "الدقهلية", "الشرقية", "القليوبية", "بورسعيد", "السويس", "أخرى"],
};

function OtpInput({ value, onChange, disabled }) {
  const refs = React.useRef([]);
  const digits = value.padEnd(6, " ").slice(0, 6).split("");
  function setAt(i, ch) {
    const arr = value.padEnd(6, " ").slice(0, 6).split("");
    arr[i] = ch;
    onChange(arr.join("").replace(/\s/g, " ").replace(/ +$/, "").trimEnd().replace(/ /g, ""));
  }
  function handleChange(i, e) {
    const v = e.target.value.replace(/\D/g, "");
    if (!v) { setAt(i, " "); return; }
    const arr = value.split("");
    arr[i] = v[v.length - 1];
    const joined = arr.join("");
    onChange(joined.slice(0, 6));
    if (i < 5 && refs.current[i + 1]) refs.current[i + 1].focus();
  }
  function handleKey(i, e) {
    if (e.key === "Backspace" && !value[i] && i > 0 && refs.current[i - 1]) {
      refs.current[i - 1].focus();
    }
  }
  function handlePaste(e) {
    const txt = (e.clipboardData.getData("text") || "").replace(/\D/g, "").slice(0, 6);
    if (txt) { e.preventDefault(); onChange(txt); const last = Math.min(txt.length, 5); if (refs.current[last]) refs.current[last].focus(); }
  }
  return (
    <div className="otpinput" dir="ltr" onPaste={handlePaste}>
      {[0, 1, 2, 3, 4, 5].map((i) => (
        <input key={i} ref={(el) => (refs.current[i] = el)} className="otpinput__box num-tabular"
          inputMode="numeric" maxLength={1} disabled={disabled}
          value={value[i] || ""} onChange={(e) => handleChange(i, e)} onKeyDown={(e) => handleKey(i, e)}
          aria-label={"Digit " + (i + 1)} />
      ))}
    </div>
  );
}

function PhoneAuthFlow({ lang, t, onAuthed, onCancel, toast }) {
  const [step, setStep] = React.useState("enter"); // enter | verify | profile
  const [dial, setDial] = React.useState("+20");
  const [number, setNumber] = React.useState("");
  const [entry, setEntry] = React.useState("");    // user input
  const [error, setError] = React.useState("");
  const [seconds, setSeconds] = React.useState(0);
  const [pName, setPName] = React.useState("");
  const [activity, setActivity] = React.useState("");
  const [gov, setGov] = React.useState("");
  const fullPhone = dial + " " + number.trim();
  // E.164 sent to the backend, e.g. "+201025228102".
  const e164 = dial.replace(/[^\d+]/g, "") + number.replace(/\D/g, "");

  React.useEffect(() => {
    if (seconds <= 0) return;
    const id = setTimeout(() => setSeconds((s) => s - 1), 1000);
    return () => clearTimeout(id);
  }, [seconds]);

  async function sendCode() {
    const digits = number.replace(/\D/g, "");
    if (digits.length < 7) { setError(t.phoneInvalid); return; }
    setError("");
    try {
      await window.api.phoneStart(e164);
      setEntry("");
      setStep("verify");
      setSeconds(30);
      if (toast) toast(t.otpSentToast);
    } catch (e) { setError(e.message); }
  }
  async function verify() {
    setError("");
    try {
      const res = await window.api.phoneVerify(e164, entry);
      if (res && res.needsProfile) { setStep("profile"); return; }
      onAuthed(res);
    } catch (e) { setError(e.message || t.otpWrong); }
  }
  async function finishProfile() {
    if (!pName.trim() || !activity.trim() || !gov) { setError(t.required); return; }
    setError("");
    try {
      const res = await window.api.phoneVerify(e164, entry, { name: pName.trim(), business: activity.trim(), governorate: gov });
      onAuthed(res);
    } catch (e) { setError(e.message); }
  }

  if (step === "profile") {
    return (
      <div className="phoneflow">
        <h1 className="authpage__title">{t.completeTitle}</h1>
        <p className="authpage__sub">{t.completeSub}</p>
        <div className="otpwa" style={{ borderStyle: "solid" }}>
          <AuthIcon name="phone" size={18} />
          <span dir="ltr" className="num-tabular">{fullPhone}</span>
        </div>
        {error && <div className="authalert"><AuthIcon name="info" size={18} />{error}</div>}
        <div className="authform">
          <Field label={t.nameLabel} req>
            <input className="input" value={pName} onChange={(e) => { setPName(e.target.value); setError(""); }} placeholder={lang === "en" ? "Karim Hassan" : "كريم حسن"} autoFocus />
          </Field>
          <Field label={t.activityLabel} req hint={t.activityHint}>
            <input className="input" value={activity} onChange={(e) => { setActivity(e.target.value); setError(""); }} placeholder={lang === "en" ? "MegaMart Stores" : "متاجر ميجامارت"} />
          </Field>
          <Field label={t.governorate} req>
            <div className="selectfield-wrap">
              <select className="selectfield" value={gov} onChange={(e) => { setGov(e.target.value); setError(""); }}>
                <option value="">{lang === "en" ? "Select…" : "اختر…"}</option>
                {AUTH_GOVS[lang].map((g, i) => <option key={i} value={AUTH_GOVS.en[i]}>{g}</option>)}
              </select>
              <span className="caret"><AuthIcon name="chevron-down" size={16} /></span>
            </div>
          </Field>
          <button type="button" className="btn btn--primary btn--lg btn--block" style={{ marginTop: 4 }} onClick={finishProfile}>
            <AuthIcon name="check" size={18} />{t.finishAccount}
          </button>
        </div>
      </div>
    );
  }

  if (step === "verify") {
    return (
      <div className="phoneflow">
        <button type="button" className="phoneflow__back" onClick={() => { setStep("enter"); setError(""); }}>
          <AuthIcon name="arrow-left" size={16} className="flip-x" />{t.changeNumber}
        </button>
        <h1 className="authpage__title">{t.otpTitle}</h1>
        <p className="authpage__sub">{t.otpSubA} <strong dir="ltr">{fullPhone}</strong> {t.otpSubB}</p>

        <div className="otpwa">
          <AuthIcon name="whatsapp" size={18} fill="currentColor" stroke={0} />
          <span>{lang === "en" ? "We sent a 6-digit code to your WhatsApp." : "أرسلنا رمزاً مكوناً من 6 أرقام إلى واتساب."}</span>
        </div>

        {error && <div className="authalert"><AuthIcon name="info" size={18} />{error}</div>}

        <OtpInput value={entry} onChange={(v) => { setEntry(v); setError(""); }} />

        <button type="button" className="btn btn--primary btn--lg btn--block" style={{ marginTop: 20 }} onClick={verify} disabled={entry.length < 6}>
          <AuthIcon name="check" size={18} />{t.verifyOtp}
        </button>

        <div className="phoneflow__resend">
          {seconds > 0 ? (
            <span>{t.resendIn} <span className="num-tabular">0:{String(seconds).padStart(2, "0")}</span></span>
          ) : (
            <button type="button" className="authswitch__link" onClick={sendCode}>{t.resendCode}</button>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="phoneflow">
      <button type="button" className="phoneflow__back" onClick={onCancel}>
        <AuthIcon name="arrow-left" size={16} className="flip-x" />{t.back}
      </button>
      <h1 className="authpage__title">{t.phoneTitle}</h1>
      <p className="authpage__sub">{t.phoneSub}</p>

      {error && <div className="authalert"><AuthIcon name="info" size={18} />{error}</div>}

      <Field label={t.phoneNumLabel} req>
        <div className="phoneinput" dir="ltr">
          <span className="phoneinput__dial num-tabular">{dial}</span>
          <input className="input" type="tel" inputMode="numeric" value={number}
            onChange={(e) => { setNumber(e.target.value); setError(""); }}
            placeholder="10 0000 0000" onKeyDown={(e) => { if (e.key === "Enter") sendCode(); }} />
        </div>
      </Field>

      <button type="button" className="btn btn--lg btn--block support__wa" style={{ marginTop: 18 }} onClick={sendCode}>
        <AuthIcon name="whatsapp" size={20} fill="currentColor" stroke={0} />{t.sendOtp}
      </button>
    </div>
  );
}

Object.assign(window, { LoginPage, AccountMenu, DEMO_ACCOUNTS });
