// MA-Trip — AuthScreen + ProfileChip. Password auth via Worker.

// Temporary auth bypass — flip to false when the email-confirm flow is ready
// to ship to real users. While true, AuthScreen renders a single "Enter" CTA
// that creates a local-only user (no server, no email). All persistence stays
// local. Set window.MA_REAL_AUTH = true in the console to opt back in.
const BYPASS_AUTH = true;

function GuestAuthScreen() {
  const { A } = window;
  const createUser = (rawName) => {
    const id = "u_local_" + Date.now().toString(36);
    const name = (rawName || "").trim() || "מטייל";
    const color = "#ff4e64";
    window.Store.set(s => ({
      ...s,
      currentUserId: id,
      accounts: [
        ...(s.accounts || []).filter(a => a.id !== id),
        { id, name, color, createdAt: Date.now() },
      ],
    }));
    if (window._haptic) window._haptic("success");
    A.showToast(`ברוכים הבאים, ${name}`, "info");
  };
  const enter = () => {
    // Ask for the user's name once on first launch instead of inventing one.
    // Was hardcoded to "אריאל" — every couples-app user saw the wrong name
    // before they ever opened the profile screen.
    A.openEditSheet({
      title: "ברוכים הבאים",
      submitLabel: "המשך",
      fields: [
        { key: "name", label: "איך לקרוא לך?", type: "text", placeholder: "השם הפרטי שלך", required: true, autoFocus: true },
      ],
      onSubmit: (v) => createUser(v && v.name),
    });
  };
  return (
    <div dir="rtl" style={{
      background: "var(--canvas)", color: "var(--ink)", minHeight: "100%",
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: "32px 22px calc(env(safe-area-inset-bottom, 0px) + 40px)", gap: 22,
      position: "relative", overflow: "hidden",
    }}>
      <div className="aurora aurora-soft" />
      <div style={{ position: "relative", zIndex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 18, maxWidth: 380, width: "100%" }}>
        <img src="assets/logo.png?v=69" alt="MA-Trip" style={{ height: 96, width: "auto" }} />
        <div style={{ textAlign: "center" }}>
          <div className="display-lg" style={{ marginBottom: 6 }}>MA-Trip</div>
          <div style={{ fontSize: 14, color: "var(--muted)", maxWidth: 320, lineHeight: 1.55 }}>
            תכנון טיולים זוגי. כל הנתונים על המכשיר — האפליקציה פועלת גם בלי אינטרנט.
          </div>
        </div>
        <button onClick={enter} type="button" className="lg-coral" style={{
          padding: "16px 36px", borderRadius: 16, border: "none",
          color: "#fff", fontSize: 17, fontWeight: 700, fontFamily: "inherit",
          cursor: "pointer", minWidth: 200,
          boxShadow: "0 14px 32px -8px rgba(255,78,100,.55)",
        }}>כניסה</button>
        <div style={{ fontSize: 11, color: "var(--muted-soft)", textAlign: "center", maxWidth: 300, lineHeight: 1.5, marginTop: 4 }}>
          חיבור עם מייל וסיסמא יחזור בקרוב.
        </div>
      </div>
    </div>
  );
}

function AuthScreenReal() {
  const { A, MaApi, loadTurnstile, renderTurnstile } = window;
  const [mode, setMode] = React.useState("signup");
  const [email, setEmail] = React.useState("");
  const [name, setName] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [tsToken, setTsToken] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  // After signup, server returns "confirm-email-sent" and we show a
  // dedicated post-signup card until the user confirms via the email link.
  const [sentToEmail, setSentToEmail] = React.useState(null);
  const tsRef = React.useRef(null);
  const tsWidgetId = React.useRef(null);

  React.useEffect(() => {
    loadTurnstile().then(() => {
      if (tsWidgetId.current && window.turnstile) {
        try { window.turnstile.remove(tsWidgetId.current); } catch (e) {}
        tsWidgetId.current = null;
      }
      if (tsRef.current) {
        tsWidgetId.current = renderTurnstile(tsRef.current, (token) => setTsToken(token));
      }
    }).catch(() => {/* dev bypass — worker accepts any token if TURNSTILE_SECRET unset */});
  }, [mode]);

  function setUserAfterAuth(user) {
    window.Store.set(s => ({
      ...s,
      currentUserId: user.id,
      accounts: [
        ...(s.accounts || []).filter(a => a.id !== user.id),
        { id: user.id, name: user.name, email: user.email, color: user.color, createdAt: Date.now() },
      ],
    }));
    A.showToast(`התחברת כ-${user.name}`, "info");
    // Fire-and-forget: pull the user's existing trip from the server so the
    // next mutation doesn't blindly create a new (duplicate) trip row.
    if (A.attachServerTrip) {
      A.attachServerTrip().catch(e => console.warn("[setUserAfterAuth] attach failed:", e));
    }
  }

  const submit = async () => {
    if (busy) return;
    const em = email.trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(em)) { A.showToast("מייל לא תקין", "error"); return; }
    if (mode === "signup") {
      if (!name.trim()) { A.showToast("חסר שם", "error"); return; }
      if (password.length < 8) { A.showToast("סיסמה חייבת 8+ תווים", "error"); return; }
      if (password !== confirm) { A.showToast("סיסמאות לא תואמות", "error"); return; }
    } else {
      if (!password) { A.showToast("חסרה סיסמה", "error"); return; }
    }
    setBusy(true);
    try {
      // Fail closed: don't send a literal "bypass" string if the Turnstile
      // widget failed to load (adblocker, network). On a misconfigured worker
      // (TURNSTILE_SECRET missing) this would otherwise let everyone through.
      if (!tsToken) {
        setBusy(false);
        A.showToast("אימות אבטחה לא נטען. נסי לרענן", "error");
        return;
      }
      const token = tsToken;
      const resp = mode === "signup"
        ? await MaApi.signup(em, name.trim(), password, token)
        : await MaApi.login(em, password, token);
      if (mode === "signup") {
        // Server replies with { ok, message:'confirm-email-sent', email }.
        // Show the "check your email" card instead of logging in.
        setSentToEmail(resp && resp.email ? resp.email : em);
        setPassword(""); setConfirm("");
        A.showToast("מייל אישור נשלח", "info");
      } else if (resp && resp.user) {
        setUserAfterAuth(resp.user);
      }
    } catch (err) {
      const map = {
        "captcha-failed": "אימות אבטחה נכשל",
        "invalid-email": "מייל לא תקין",
        "invalid-name": "שם לא תקין",
        "weak-password": "סיסמה חייבת 8+ תווים",
        "email-taken": "כתובת המייל כבר רשומה",
        "confirm-email-already-sent": "כבר נשלח אליך מייל אישור — בדקי בתיבת הדואר",
        "bad-credentials": "מייל או סיסמה שגויים",
        "email-not-confirmed": "המייל עוד לא אושר. בדקי בתיבת הדואר.",
        "missing-expected-version": "נדרשת סנכרון מחדש. נסי שוב מיד",
        "account-disabled": "החשבון מושבת",
        "email-send-failed": "שליחת המייל נכשלה — נסי שוב",
        "too-many-requests": "יותר מדי בקשות. נסה/י עוד מעט.",
        "private-beta": "כתובת זו לא ברשימת הbeta. פנה/י לאריאל.",
      };
      A.showToast(map[err.code] || ("שגיאה: " + (err.code || err.message)), "error");
      if (tsWidgetId.current && window.turnstile) {
        try { window.turnstile.reset(tsWidgetId.current); } catch (e) {}
      }
      setTsToken(null);
    } finally { setBusy(false); }
  };

  // Post-signup confirmation card. Stays until the user clicks the link in
  // their email (the app-load handler in app.jsx detects #confirm=<token>
  // and activates the account, after which the user can return here to log in).
  if (sentToEmail) {
    return (
      <div dir="rtl" style={{
        background: "var(--canvas)", color: "var(--ink)", minHeight: "100%",
        display: "flex", flexDirection: "column", alignItems: "center",
        padding: "44px 22px calc(env(safe-area-inset-bottom, 0px) + 40px)", gap: 18,
      }}>
        <img src="assets/logo.png?v=69" alt="MA-Trip" style={{ height: 64, width: "auto", marginTop: 8 }} />
        <div className="lg-bento" style={{ padding: "32px 22px", maxWidth: 360, width: "100%", textAlign: "center", display: "flex", flexDirection: "column", gap: 14, alignItems: "center" }}>
          <div style={{
            width: 64, height: 64, borderRadius: 9999,
            background: "linear-gradient(135deg, #ff7a8b, var(--coral))",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "#fff", fontSize: 28,
            boxShadow: "0 10px 24px -6px rgba(255,78,100,.45)",
          }} aria-hidden="true">✉</div>
          <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-.02em" }}>בדקי את המייל</div>
          <div style={{ fontSize: 14, color: "var(--muted)", lineHeight: 1.55 }}>
            שלחנו קישור אישור ל-<span dir="ltr" style={{ unicodeBidi: "isolate", fontFamily: "var(--mono)", fontSize: 13 }}>{sentToEmail}</span>.
            <br />לחצי על הקישור כדי להפעיל את החשבון, וחזרי לכאן להתחבר עם המייל והסיסמא.
          </div>
          <button onClick={() => { setSentToEmail(null); setMode("login"); }} className="lg-coral" type="button" style={{
            padding: "12px 24px", borderRadius: 12, border: "none",
            color: "#fff", fontWeight: 700, fontSize: 15, cursor: "pointer", fontFamily: "inherit",
          }}>אישרתי — להתחברות</button>
          <button onClick={() => setSentToEmail(null)} type="button" style={{
            background: "transparent", border: "none", color: "var(--action)",
            fontSize: 13, fontWeight: 500, cursor: "pointer", fontFamily: "inherit",
            padding: "6px 12px",
          }}>הרשמה מחדש</button>
        </div>
      </div>
    );
  }

  const inputStyle = {
    padding: "13px 14px", border: "0.5px solid rgba(0,0,0,.18)", borderRadius: 10,
    background: "#fff", fontSize: 16, fontFamily: "inherit", direction: "ltr",
    textAlign: "right", outline: "none", width: "100%", boxSizing: "border-box",
    WebkitAppearance: "none", appearance: "none",
  };
  const labelStyle = {
    fontSize: 13, color: "var(--muted)", fontWeight: 500, marginBottom: 6, display: "block",
  };

  return (
    <div dir="rtl" style={{
      background: "var(--canvas)", color: "var(--ink)", minHeight: "100%",
      display: "flex", flexDirection: "column", alignItems: "center",
      padding: "32px 22px calc(env(safe-area-inset-bottom, 0px) + 40px)", gap: 14,
    }}>
      <img src="assets/logo.png?v=69" alt="MA-Trip" style={{ height: 84, width: "auto", marginTop: 12 }} />
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-.02em" }}>MA-Trip</div>
        <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 4 }}>תכנון טיולים זוגי / משפחתי</div>
      </div>

      <div style={{
        display: "flex", background: "var(--surface-soft)",
        borderRadius: 9999, padding: 4, marginTop: 8, width: "100%", maxWidth: 360,
      }}>
        {[
          { k: "signup", label: "הרשמה" },
          { k: "login",  label: "התחברות" },
        ].map(t => {
          const active = mode === t.k;
          return (
            <button key={t.k} onClick={() => setMode(t.k)} style={{
              flex: 1, padding: "10px", borderRadius: 9999, border: "none",
              background: active ? "var(--canvas)" : "transparent",
              color: active ? "var(--ink)" : "var(--muted)",
              fontWeight: 600, fontSize: 14, cursor: "pointer", fontFamily: "inherit",
              boxShadow: active ? "0 2px 8px rgba(0,0,0,.08)" : "none",
              transition: "all .18s ease",
            }}>{t.label}</button>
          );
        })}
      </div>

      <div className="lg-light" style={{
        borderRadius: 18, padding: "20px", width: "100%", maxWidth: 360,
        display: "flex", flexDirection: "column", gap: 14,
      }}>
        {mode === "signup" && (
          <div>
            <label style={labelStyle}>שם להצגה</label>
            <input type="text" value={name} onChange={e => setName(e.target.value)}
              placeholder="אריאל" autoComplete="name" autoFocus
              style={{ ...inputStyle, direction: "rtl", textAlign: "right" }} />
          </div>
        )}
        <div>
          <label style={labelStyle}>אימייל</label>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)}
            placeholder="you@example.com" autoComplete="email" inputMode="email"
            autoFocus={mode === "login"}
            style={inputStyle} />
        </div>
        <div>
          <label style={labelStyle}>סיסמה {mode === "signup" ? "(8+ תווים)" : ""}</label>
          <input type="password" value={password} onChange={e => setPassword(e.target.value)}
            placeholder="••••••••" autoComplete={mode === "signup" ? "new-password" : "current-password"}
            onKeyDown={e => { if (e.key === "Enter" && mode === "login") submit(); }}
            style={inputStyle} />
        </div>
        {mode === "signup" && (
          <div>
            <label style={labelStyle}>אימות סיסמה</label>
            <input type="password" value={confirm} onChange={e => setConfirm(e.target.value)}
              placeholder="••••••••" autoComplete="new-password"
              onKeyDown={e => { if (e.key === "Enter") submit(); }}
              style={inputStyle} />
          </div>
        )}

        <div ref={tsRef} style={{ display: "flex", justifyContent: "center", minHeight: 0 }} />

        <button onClick={submit} disabled={busy} className="lg-coral" style={{
          padding: "14px", borderRadius: 12, border: "none", color: "#fff",
          fontSize: 16, fontWeight: 700, cursor: busy ? "default" : "pointer",
          fontFamily: "inherit", opacity: busy ? .6 : 1,
        }}>{busy ? "..." : (mode === "signup" ? "צור חשבון" : "התחבר/י")}</button>
      </div>

      <div style={{ fontSize: 11, color: "var(--muted-soft)", textAlign: "center", maxWidth: 320, lineHeight: 1.5, marginTop: 4 }}>
        החשבון מאובטח ב-Cloudflare. הסיסמה מוצפנת PBKDF2 ולא נשמרת כטקסט גולמי.
      </div>
    </div>
  );
}

function ProfileChip() {
  const { useStore, A, currentUser } = window;
  useStore(s => s.currentUserId);
  const u = currentUser();
  if (!u) return null;
  return (
    <button onClick={() => A.openProfile()} aria-label="פרופיל" style={{
      display: "flex", alignItems: "center", gap: 8,
      padding: "4px 10px 4px 4px", borderRadius: 9999,
      background: "var(--surface-soft)", border: "1px solid var(--hairline)",
      cursor: "pointer", fontFamily: "inherit",
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 9999,
        background: u.color || "var(--coral)", color: "#fff",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 12, fontWeight: 700,
      }}>{(u.name || "?").charAt(0)}</div>
      <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)" }}>{u.name}</span>
    </button>
  );
}

// Pick the active screen based on the bypass flag.
function AuthScreen() {
  if (BYPASS_AUTH && !window.MA_REAL_AUTH) return <GuestAuthScreen />;
  return <AuthScreenReal />;
}

window.AuthScreen = AuthScreen;
window.ProfileChip = ProfileChip;
