/* ============================================================
   Landing (home) + Auth (login / register)
   ============================================================ */

function HowStep({ n, title, body, icon }) {
  return (
    <div className="card card-pad" style={{ display: "grid", gap: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <span style={{ width: 40, height: 40, borderRadius: 11, background: "var(--primary-soft)", color: "var(--primary)", display: "grid", placeItems: "center" }}>{icon}</span>
        <span style={{ fontFamily: "var(--mono)", fontSize: 13, fontWeight: 600, color: "var(--text-3)" }}>0{n}</span>
      </div>
      <div style={{ fontWeight: 700, fontSize: 16.5, letterSpacing: "-0.01em" }}>{title}</div>
      <div className="mut" style={{ fontSize: 14.5, lineHeight: 1.55 }}>{body}</div>
    </div>
  );
}

function Landing({ goView }) {
  return (
    <div>
      {/* Hero */}
      <section style={{ background: "linear-gradient(180deg, #fff 0%, var(--bg) 100%)", borderBottom: "1px solid var(--border)" }}>
        <div className="wrap hero" style={{ padding: "72px 24px 60px" }}>
          <div>
            <span className="eyebrow">{Ic.shield({ s: 14 })} {t("landing.eyebrow")}</span>
            <h1 style={{ fontSize: 52, lineHeight: 1.05, letterSpacing: "-0.035em", margin: "20px 0 0", fontWeight: 800 }}
                dangerouslySetInnerHTML={{ __html: t("landing.heroTitleHtml") }} />
            <p className="mut" style={{ fontSize: 18, lineHeight: 1.55, margin: "20px 0 32px", maxWidth: 480 }}>
              {t("landing.heroText")}
            </p>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              <Btn kind="primary" size="lg" onClick={() => goView("wizard")} iconRight={Ic.arrow({ s: 18 })}>{t("landing.cta1")}</Btn>
              <Btn kind="ghost" size="lg" onClick={() => goView("dashboard")} icon={Ic.layers({ s: 18 })}>{t("landing.cta2")}</Btn>
            </div>
            <div style={{ display: "flex", gap: 24, marginTop: 32, flexWrap: "wrap" }}>
              {[t("landing.check1"), t("landing.check2"), t("landing.check3")].map(tx => (
                <div key={tx} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13.5, color: "var(--text-2)", fontWeight: 500 }}>
                  <span style={{ color: "var(--green)" }}>{Ic.check({ s: 15 })}</span>{tx}
                </div>
              ))}
            </div>
          </div>

          {/* Hero visual: mock certificate */}
          <div style={{ position: "relative" }}>
            <div className="card" style={{ boxShadow: "var(--shadow-lg)", padding: 0, overflow: "hidden", transform: "rotate(-1.2deg)" }}>
              <div style={{ background: "linear-gradient(135deg, var(--primary), var(--primary-800))", padding: "18px 22px", color: "#fff", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, fontWeight: 700, whiteSpace: "nowrap" }}>{Ic.lock({ s: 18 })} {t("landing.cardTitle")}</div>
                <span style={{ fontSize: 12, opacity: .85, fontFamily: "var(--mono)" }}>DV · RSA 2048</span>
              </div>
              <div style={{ padding: 22, display: "grid", gap: 14 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="mut" style={{ fontSize: 13 }}>{t("landing.cardDomain")}</span>
                  <span style={{ fontFamily: "var(--mono)", fontWeight: 600 }}>acmeyazilim.com</span>
                </div>
                <hr className="divider" />
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="mut" style={{ fontSize: 13 }}>{t("landing.cardStatus")}</span>
                  <Badge tone="green">{Ic.check({ s: 12 })} {t("landing.cardActive")}</Badge>
                </div>
                <hr className="divider" />
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="mut" style={{ fontSize: 13 }}>{t("landing.cardValidity")}</span>
                  <span style={{ fontWeight: 600 }}>{t("landing.cardLeft")}</span>
                </div>
                <div style={{ height: 8, background: "var(--bg-2)", borderRadius: 999, overflow: "hidden" }}>
                  <div style={{ width: "87%", height: "100%", background: "var(--green)", borderRadius: 999 }} />
                </div>
              </div>
            </div>
            <div className="card hide-mobile" style={{ position: "absolute", top: "50%", left: -44, transform: "translateY(-50%) rotate(2deg)", padding: "12px 16px", display: "flex", alignItems: "center", gap: 10, boxShadow: "var(--shadow-lg)" }}>
              <span style={{ color: "var(--primary)" }}>{Ic.bell({ s: 18 })}</span>
              <div style={{ fontSize: 12.5 }}><div style={{ fontWeight: 700 }}>{t("landing.cardRemindT")}</div><div className="hint">{t("landing.cardRemindS")}</div></div>
            </div>
          </div>
        </div>
      </section>

      {/* Reklam (leaderboard) — hero altı */}
      <div className="wrap" style={{ padding: "28px 24px 0" }}><AdSlot format="leaderboard" /></div>

      {/* How it works */}
      <section className="wrap" style={{ padding: "64px 24px" }}>
        <div style={{ textAlign: "center", marginBottom: 40 }}>
          <span className="eyebrow">{t("landing.howEyebrow")}</span>
          <h2 style={{ fontSize: 32, letterSpacing: "-0.03em", margin: "14px 0 0" }}>{t("landing.howTitle")}</h2>
        </div>
        <div className="grid grid-3" style={{ gap: 20 }}>
          <HowStep n={1} icon={Ic.globe({ s: 19 })} title={t("landing.step1t")} body={t("landing.step1b")} />
          <HowStep n={2} icon={Ic.globe({ s: 19 })} title={t("landing.step2t")} body={t("landing.step2b")} />
          <HowStep n={3} icon={Ic.download({ s: 19 })} title={t("landing.step3t")} body={t("landing.step3b")} />
        </div>
        <div style={{ textAlign: "center", marginTop: 40 }}>
          <Btn kind="primary" size="lg" onClick={() => goView("wizard")} iconRight={Ic.arrow({ s: 18 })}>{t("landing.start")}</Btn>
        </div>
      </section>
    </div>
  );
}

/* ----------------------------- AUTH ----------------------------- */
function Auth({ mode, goView, onAuth }) {
  const isReg = mode === "register";
  const resetToken = (function () { try { return new URLSearchParams(location.search).get("token") || ""; } catch (e) { return ""; } })();
  const [email, setEmail] = useState("");
  const [pwd, setPwd] = useState("");
  const [agree, setAgree] = useState(false);   // kayıt: Hizmet Şartları onayı (zorunlu)
  const [view, setView] = useState(resetToken ? "reset" : "form");   // form | forgot | sent | reset
  const [resetMail, setResetMail] = useState("");
  const [npw, setNpw] = useState("");
  const [npw2, setNpw2] = useState("");
  const [resetting, setResetting] = useState(false);
  const doReset = () => {
    if (npw.trim().length < 6) { window.sslToast && window.sslToast("Şifre en az 6 karakter olmalı."); return; }
    if (npw !== npw2) { window.sslToast && window.sslToast("Şifreler eşleşmiyor."); return; }
    setResetting(true);
    (window.sslReset ? window.sslReset(resetToken, npw) : Promise.resolve({ ok: false })).then(function (r) {
      setResetting(false);
      if (r && r.ok) { window.sslToast && window.sslToast("Şifreniz güncellendi, giriş yapabilirsiniz.", true); try { history.replaceState(null, "", location.pathname); } catch (e) {} setView("form"); }
      else window.sslToast && window.sslToast((r && r.error) || "Bağlantı geçersiz veya süresi dolmuş.");
    });
  };
  const submit = () => {
    if (isReg && !agree) { window.sslToast && window.sslToast(t("terms.mustAccept")); return; }
    if (window.sslAuth) return window.sslAuth(isReg ? "register" : "login", email.trim(), pwd);
    onAuth({ email: email || "kerim@acmeyazilim.com" });
  };
  const sendReset = () => { if (window.sslForgot) window.sslForgot(resetMail.trim()); setView("sent"); };

  const resetOk = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(resetMail.trim());

  /* ---- Reset-password: e-postadaki linkten gelen token ile yeni şifre ---- */
  if (view === "reset") {
    return (
      <div className="wrap" style={{ maxWidth: 440, padding: "60px 24px 100px" }}>
        <div className="card card-pad fade-up" style={{ padding: 32 }}>
          <div style={{ textAlign: "center", marginBottom: 24 }}>
            <div className="brand-mark" style={{ width: 44, height: 44, margin: "0 auto 16px", borderRadius: 12 }}>{Ic.lock({ s: 24 })}</div>
            <h2 style={{ margin: "0 0 6px", fontSize: 23, letterSpacing: "-0.02em" }}>Yeni şifre belirle</h2>
            <p className="mut" style={{ margin: 0, fontSize: 14.5 }}>Hesabınız için yeni bir şifre girin.</p>
          </div>
          <div style={{ display: "grid", gap: 14 }}>
            <Field label="Yeni şifre">
              <div className="input-affix"><span className="prefix">{Ic.lock({ s: 17 })}</span>
                <input className="input" type="password" style={{ paddingLeft: 42 }} placeholder="En az 6 karakter" value={npw}
                       onChange={e => setNpw(e.target.value)} /></div>
            </Field>
            <Field label="Yeni şifre (tekrar)">
              <div className="input-affix"><span className="prefix">{Ic.lock({ s: 17 })}</span>
                <input className="input" type="password" style={{ paddingLeft: 42 }} placeholder="Şifreyi tekrar girin" value={npw2}
                       onChange={e => setNpw2(e.target.value)} onKeyDown={e => { if (e.key === "Enter") doReset(); }} /></div>
            </Field>
            <Btn kind="primary" size="lg" block disabled={resetting} onClick={doReset}>{resetting ? "Güncelleniyor…" : "Şifremi güncelle"}</Btn>
          </div>
          <p className="mut" style={{ textAlign: "center", fontSize: 14, marginTop: 20, marginBottom: 0 }}>
            <a style={{ color: "var(--primary)", fontWeight: 600, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5 }}
               onClick={() => { try { history.replaceState(null, "", location.pathname); } catch (e) {} setView("form"); }}>{Ic.back({ s: 15 })} {t("auth.fpBack")}</a>
          </p>
        </div>
      </div>
    );
  }

  /* ---- Forgot-password: enter e-mail ---- */
  if (view === "forgot") {
    return (
      <div className="wrap" style={{ maxWidth: 440, padding: "60px 24px 100px" }}>
        <div className="card card-pad fade-up" style={{ padding: 32 }}>
          <div style={{ textAlign: "center", marginBottom: 24 }}>
            <div className="brand-mark" style={{ width: 44, height: 44, margin: "0 auto 16px", borderRadius: 12 }}>{Ic.lock({ s: 24 })}</div>
            <h2 style={{ margin: "0 0 6px", fontSize: 23, letterSpacing: "-0.02em" }}>{t("auth.fpTitle")}</h2>
            <p className="mut" style={{ margin: 0, fontSize: 14.5 }}>{t("auth.fpSub")}</p>
          </div>
          <div style={{ display: "grid", gap: 14 }}>
            <Field label={t("auth.email")}>
              <div className="input-affix"><span className="prefix">{Ic.mail({ s: 17 })}</span>
                <input className="input" style={{ paddingLeft: 42 }} placeholder="siz@sirket.com" value={resetMail}
                       onChange={e => setResetMail(e.target.value)} onKeyDown={e => { if (e.key === "Enter" && resetOk) sendReset(); }} /></div>
            </Field>
            <Btn kind="primary" size="lg" block disabled={!resetOk} onClick={sendReset}>{t("auth.fpSend")}</Btn>
          </div>
          <p className="mut" style={{ textAlign: "center", fontSize: 14, marginTop: 20, marginBottom: 0 }}>
            <a style={{ color: "var(--primary)", fontWeight: 600, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5 }}
               onClick={() => setView("form")}>{Ic.back({ s: 15 })} {t("auth.fpBack")}</a>
          </p>
        </div>
      </div>
    );
  }

  /* ---- Forgot-password: link sent confirmation ---- */
  if (view === "sent") {
    return (
      <div className="wrap" style={{ maxWidth: 440, padding: "60px 24px 100px" }}>
        <div className="card card-pad fade-up" style={{ padding: 32, textAlign: "center" }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--green-soft)", color: "var(--green)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}>{Ic.mail({ s: 28 })}</div>
          <h2 style={{ margin: "0 0 8px", fontSize: 22, letterSpacing: "-0.02em" }}>{t("auth.sentTitle")}</h2>
          <p className="mut" style={{ margin: "0 auto", fontSize: 14.5, maxWidth: 320, lineHeight: 1.55 }}>
            <span className="code">{resetMail}</span> {t("auth.sentBody")}
          </p>
          <div style={{ display: "flex", gap: 10, padding: "12px 14px", margin: "20px 0 4px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--r)", textAlign: "left" }}>
            <span style={{ color: "var(--text-3)", flex: "none", marginTop: 1 }}>{Ic.clock({ s: 17 })}</span>
            <div className="hint" style={{ lineHeight: 1.5 }}>{t("auth.sentNote")}</div>
          </div>
          <div style={{ display: "grid", gap: 10, marginTop: 18 }}>
            <Btn kind="ghost" block onClick={() => setView("forgot")}>{t("auth.resend")}</Btn>
            <Btn kind="primary" block onClick={() => setView("form")} iconRight={Ic.arrow({ s: 16 })}>{t("auth.fpBack")}</Btn>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="wrap" style={{ maxWidth: 440, padding: "60px 24px 100px" }}>
      <div className="card card-pad fade-up" style={{ padding: 32 }}>
        <div style={{ textAlign: "center", marginBottom: 24 }}>
          <div className="brand-mark" style={{ width: 44, height: 44, margin: "0 auto 16px", borderRadius: 12 }}>{Ic.shield({ s: 24 })}</div>
          <h2 style={{ margin: "0 0 6px", fontSize: 23, letterSpacing: "-0.02em" }}>{isReg ? t("auth.regTitle") : t("auth.loginTitle")}</h2>
          <p className="mut" style={{ margin: 0, fontSize: 14.5 }}>{isReg ? t("auth.regSub") : t("auth.loginSub")}</p>
        </div>
        <div style={{ display: "grid", gap: 14 }}>
          <Field label={t("auth.email")}>
            <div className="input-affix"><span className="prefix">{Ic.mail({ s: 17 })}</span>
              <input className="input" style={{ paddingLeft: 42 }} placeholder="siz@sirket.com" value={email} onChange={e => setEmail(e.target.value)} /></div>
          </Field>
          <Field label={t("auth.password")}>
            <div className="input-affix"><span className="prefix">{Ic.lock({ s: 17 })}</span>
              <input className="input" type="password" style={{ paddingLeft: 42 }} placeholder="••••••••" value={pwd} onChange={e => setPwd(e.target.value)} /></div>
            {!isReg && (
              <div style={{ textAlign: "right", marginTop: 8 }}>
                <a style={{ color: "var(--primary)", fontWeight: 600, fontSize: 13.5, cursor: "pointer" }}
                   onClick={() => { setResetMail(email); setView("forgot"); }}>{t("auth.forgot")}</a>
              </div>
            )}
          </Field>
          {isReg && (
            <Check checked={agree} onChange={setAgree}>
              {t("terms.consent")}{" "}
              <a href={(window.PAGES && window.PAGES.terms) || "/kosullar"} target="_blank" rel="noopener noreferrer"
                 style={{ color: "var(--primary)", fontWeight: 600 }}>{t("terms.title")}</a>
            </Check>
          )}
          <Btn kind="primary" size="lg" block onClick={submit} disabled={isReg && !agree}>{isReg ? t("auth.register") : t("auth.login")}</Btn>
        </div>
        <p className="mut" style={{ textAlign: "center", fontSize: 14, marginTop: 20, marginBottom: 0 }}>
          {isReg ? t("auth.haveAccount") : t("auth.noAccount")}
          <a style={{ color: "var(--primary)", fontWeight: 600, cursor: "pointer" }} onClick={() => goView(isReg ? "login" : "register")}>
            {isReg ? t("auth.doLogin") : t("auth.doRegister")}
          </a>
        </p>
      </div>
      <p className="mut" style={{ textAlign: "center", fontSize: 13, marginTop: 18 }}>
        {t("auth.guest1")}<a style={{ color: "var(--primary)", fontWeight: 600, cursor: "pointer" }} onClick={() => goView("wizard")}>{t("auth.guest2")}</a>.
      </p>
    </div>
  );
}

/* ----------------------------- 404 ----------------------------- */
function NotFound({ goView }) {
  return (
    <div className="wrap" style={{ minHeight: "62vh", display: "grid", placeItems: "center", padding: "80px 24px 120px", textAlign: "center" }}>
      <div style={{ maxWidth: 520 }}>
        <div style={{ width: 76, height: 76, borderRadius: 20, background: "var(--primary-soft)", color: "var(--primary)", display: "grid", placeItems: "center", margin: "0 auto 22px" }}>{Ic.shield({ s: 38 })}</div>
        <div style={{ fontFamily: "var(--mono)", fontSize: 64, fontWeight: 800, letterSpacing: "-0.04em", color: "var(--primary)", lineHeight: 1 }}>{t("nf.code")}</div>
        <h1 style={{ fontSize: 28, letterSpacing: "-0.03em", margin: "14px 0 10px" }}>{t("nf.title")}</h1>
        <p className="mut" style={{ fontSize: 16, lineHeight: 1.6, margin: "0 0 28px" }}>{t("nf.sub")}</p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <Btn kind="primary" size="lg" onClick={() => goView("home")} icon={Ic.arrow({ s: 18 })}>{t("nf.home")}</Btn>
          <Btn kind="ghost" size="lg" onClick={() => goView("wizard")} icon={Ic.shield({ s: 17 })}>{t("nf.wizard")}</Btn>
          <Btn kind="ghost" size="lg" onClick={() => goView("blog")} icon={Ic.file({ s: 17 })}>{t("nf.blog")}</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Landing, Auth, NotFound });
