// screens-auth.jsx — Login + Signup + Forgot password

function AuthSide({ lang }) {
  const isAr = lang === "ar";
  return (
    <aside className="auth-side">
      <div className="brand">
        <div className="brand-mark">R</div>
        <div className="brand-name">
          <b style={{ color: "inherit" }}>{isAr ? "روّج برو" : "Rawj Pro"}</b>
          <span style={{ color: "rgba(255,255,255,.7)" }}>rawj.pro</span>
        </div>
      </div>
      <h2>{isAr ? "حسابك الإعلاني — ما يوقف أبداً." : "Your ad accounts — never go dark."}</h2>
      <p>
        {isAr
          ? "روّج برو يراقب كل حساباتك الإعلانية على مدار الساعة، ويبعتلك تنبيه فوري لو فيه مديونية أو حساب موقوف، قبل ما إعلاناتك تتأثر."
          : "Rawj Pro watches every ad account 24/7. Get alerted on debts and suspensions before your ads stop."}
      </p>
      <div className="auth-feats">
        <div><b>🛡️ {isAr ? "صلاحية قراءة فقط" : "Read-only"}</b><span>{isAr ? "صفر خطر إيقاف" : "Zero suspension risk"}</span></div>
        <div><b>⚡ {isAr ? "تنبيهات لحظية" : "Real-time alerts"}</b><span>{isAr ? "تليجرام · واتساب · إيميل" : "Telegram · WhatsApp · Email"}</span></div>
        <div><b>📊 {isAr ? "تقارير عربية" : "Arabic reports"}</b><span>{isAr ? "صباحياً بالعناصر اللي تختارها" : "Daily with custom metrics"}</span></div>
        <div><b>🌐 4 {isAr ? "منصات" : "platforms"}</b><span>Meta · Google · TikTok · Snap</span></div>
      </div>
    </aside>
  );
}

function LoginScreen({ lang, setRoute, onAuthSuccess }) {
  const isAr = lang === "ar";
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setErr(null); setBusy(true);
    try {
      const data = await API.login({ email, password });
      onAuthSuccess(data.user);
    } catch (e) {
      setErr(e.message || (isAr ? "فشل تسجيل الدخول" : "Login failed"));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="auth-shell">
      <AuthSide lang={lang} />
      <main className="auth-form">
        <form className="auth-form-inner" onSubmit={submit}>
          <h1>{isAr ? "تسجيل الدخول" : "Sign in"}</h1>
          <p className="auth-sub">{isAr ? "ادخل لحسابك على روّج برو." : "Sign in to your Rawj Pro account."}</p>

          {err && <div className="err">{err}</div>}

          <div className="field">
            <label>{isAr ? "البريد الإلكتروني" : "Email"}</label>
            <input type="email" autoComplete="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="you@company.com" />
          </div>

          <div className="field">
            <label>{isAr ? "كلمة المرور" : "Password"}</label>
            <input type="password" autoComplete="current-password" required value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" />
          </div>

          <div className="field-row">
            <label><input type="checkbox" defaultChecked /> {isAr ? "تذكرني" : "Remember me"}</label>
            <a onClick={() => setRoute("forgot")}>{isAr ? "نسيت كلمة المرور؟" : "Forgot password?"}</a>
          </div>

          <button className="btn btn-primary btn-lg" type="submit" disabled={busy} style={{ width: "100%", justifyContent: "center" }}>
            {busy ? (isAr ? "جاري الدخول..." : "Signing in...") : (isAr ? "تسجيل الدخول" : "Sign in")}
          </button>

          <div className="auth-divider">{isAr ? "أو" : "or"}</div>

          <a className="btn btn-lg" href={`https://t.me/${window.RAWJ_CONFIG.BOT_USERNAME}`} target="_blank" rel="noopener" style={{ width: "100%", justifyContent: "center" }}>
            <Icon.send size={14} /> {isAr ? "افتح بوت التليجرام" : "Open Telegram bot"}
          </a>

          <div className="switch-link">
            {isAr ? "ما عندك حساب؟" : "Don't have an account?"} <a onClick={() => setRoute("signup")}>{isAr ? "أنشئ حساب جديد" : "Create one"}</a>
          </div>
        </form>
      </main>
    </div>
  );
}

function SignupScreen({ lang, setRoute, onAuthSuccess }) {
  const isAr = lang === "ar";
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setErr(null);
    if (password.length < 8) {
      setErr(isAr ? "كلمة المرور لازم 8 خانات على الأقل" : "Password must be 8+ characters");
      return;
    }
    setBusy(true);
    try {
      const data = await API.signup({ name, email, password });
      onAuthSuccess(data.user);
    } catch (e) {
      setErr(e.message || (isAr ? "فشل إنشاء الحساب" : "Signup failed"));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="auth-shell">
      <AuthSide lang={lang} />
      <main className="auth-form">
        <form className="auth-form-inner" onSubmit={submit}>
          <h1>{isAr ? "أنشئ حسابك" : "Create your account"}</h1>
          <p className="auth-sub">
            {isAr ? "ابدأ مجاناً — 7 أيام تجربة على منصة من اختيارك." : "Start free — 7-day trial on one platform."}
          </p>

          {err && <div className="err">{err}</div>}

          <div className="field">
            <label>{isAr ? "الاسم" : "Full name"}</label>
            <input type="text" autoComplete="name" required value={name} onChange={e => setName(e.target.value)} placeholder={isAr ? "محمد العمري" : "Mohamed Al-Omari"} />
          </div>

          <div className="field">
            <label>{isAr ? "البريد الإلكتروني" : "Email"}</label>
            <input type="email" autoComplete="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="you@company.com" />
          </div>

          <div className="field">
            <label>{isAr ? "كلمة المرور" : "Password"}</label>
            <input type="password" autoComplete="new-password" required minLength={8} value={password} onChange={e => setPassword(e.target.value)} placeholder={isAr ? "8 خانات على الأقل" : "8+ characters"} />
          </div>

          <button className="btn btn-primary btn-lg" type="submit" disabled={busy} style={{ width: "100%", justifyContent: "center" }}>
            {busy ? (isAr ? "جاري الإنشاء..." : "Creating...") : (isAr ? "أنشئ حسابي" : "Create account")}
          </button>

          <p style={{ fontSize: 11.5, color: "var(--muted)", margin: "14px 0 0", textAlign: "center" }}>
            {isAr ? "بإنشاء الحساب، أنت توافق على شروط الاستخدام وسياسة الخصوصية." : "By signing up, you agree to the Terms and Privacy Policy."}
          </p>

          <div className="switch-link">
            {isAr ? "عندك حساب بالفعل؟" : "Already have an account?"} <a onClick={() => setRoute("login")}>{isAr ? "تسجيل الدخول" : "Sign in"}</a>
          </div>
        </form>
      </main>
    </div>
  );
}

function ForgotScreen({ lang, setRoute }) {
  const isAr = lang === "ar";
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);

  async function submit(e) {
    e.preventDefault();
    // For MVP: just show a confirmation. Real password reset is v1.1.
    setSent(true);
  }

  return (
    <div className="auth-shell">
      <AuthSide lang={lang} />
      <main className="auth-form">
        <form className="auth-form-inner" onSubmit={submit}>
          <h1>{isAr ? "استعادة كلمة المرور" : "Reset password"}</h1>
          <p className="auth-sub">
            {isAr ? "اكتب بريدك الإلكتروني وهنبعتلك خطوات إعادة تعيين كلمة المرور." : "Enter your email and we'll send reset instructions."}
          </p>

          {sent ? (
            <div className="ok">
              {isAr
                ? "✅ لو الإيميل ده موجود عندنا، هيوصلك رابط الاستعادة خلال دقايق. تواصل معنا لو ما وصلش."
                : "✅ If that email is on file, you'll get reset instructions shortly. Contact us if it doesn't arrive."}
            </div>
          ) : (
            <>
              <div className="field">
                <label>{isAr ? "البريد الإلكتروني" : "Email"}</label>
                <input type="email" autoComplete="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="you@company.com" />
              </div>
              <button className="btn btn-primary btn-lg" type="submit" style={{ width: "100%", justifyContent: "center" }}>
                {isAr ? "أرسل رابط الاستعادة" : "Send reset link"}
              </button>
            </>
          )}

          <div className="switch-link">
            <a onClick={() => setRoute("login")}>{isAr ? "← الرجوع لتسجيل الدخول" : "← Back to sign in"}</a>
          </div>
        </form>
      </main>
    </div>
  );
}

window.LoginScreen = LoginScreen;
window.SignupScreen = SignupScreen;
window.ForgotScreen = ForgotScreen;
