/* ============================================================
   EBTR — Author Portal: app shell (auth, routing, modals)
   ============================================================ */
const PORTAL_LS = "ebtr_author_authed_v1";

function PModal({ title, subtitle, children, onClose }) {
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(8,8,10,0.74)", backdropFilter: "blur(6px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 460, background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderTop: "3px solid var(--ebt-orange)", padding: "34px 36px 38px" }}>
        <div style={{ marginBottom: 18 }}><PBar orientation="vertical" thickness={8} /></div>
        <h2 style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 24, color: "var(--white)", margin: "0 0 10px", textWrap: "balance" }}>{title}</h2>
        {subtitle && <p style={{ fontFamily: "var(--font-body)", fontSize: 15.5, lineHeight: 1.6, color: "var(--text-secondary)", margin: "0 0 24px" }}>{subtitle}</p>}
        {children}
      </div>
    </div>
  );
}

function PortalApp() {
  const LIVE = !!window.EBTR_AUTH;
  const [authed, setAuthed] = React.useState(() => { if (window.EBTR_AUTH) return false; try { return localStorage.getItem(PORTAL_LS) === "1"; } catch (e) { return false; } });
  const [authState, setAuthState] = React.useState(LIVE ? "checking" : "demo");
  const [route, setRoute] = React.useState({ name: "dashboard" });
  const [guideOpen, setGuideOpen] = React.useState(false);
  const [confirm, setConfirm] = React.useState(false);
  const [me, setMe] = React.useState(window.EBTR_AUTHOR.me);
  const saveProfile = (patch) => {
    setMe((m) => ({ ...m, ...patch, approved: false }));
    var email = patch.email || me.email;
    if (!LIVE) { alert("Saved locally (demo mode — not connected to the database). email=" + email); return; }
    if (!window.EBTR_SAVE_PROFILE) { alert("Save function missing — old build deployed. Re-deploy the latest files."); return; }
    if (!email) { alert("No email on your session — cannot save. Sign out and sign in with Google again."); return; }
    window.EBTR_SAVE_PROFILE({ email: email, name: patch.name, title: patch.title, bio: patch.bio, badges: patch.badges, portraitUrl: patch.portraitUrl })
      .then(function () { /* success — the inline ✓ Saved shows */ })
      .catch(function (e) { alert("Save to database failed: " + (e && e.message ? e.message : e)); });
  };

  // Live auth: @ebthub.com (Google) or invited author (email link)
  React.useEffect(() => {
    if (!LIVE) return;
    window.EBTR_AUTH.completeLinkIfPresent().catch(function () {});
    return window.EBTR_AUTH.onChange(function (v) {
      if (!v) { setAuthed(false); setAuthState("out"); return; }
      setMe(function (m) { return Object.assign({}, m, { name: v.name || m.name, email: v.email, initials: (v.name || v.email || "?").split(/[ @.]/).filter(Boolean).slice(0, 2).map(function (x) { return x[0]; }).join("").toUpperCase() }); });
      setAuthed(true); setAuthState("in");
      // load this author's saved profile from Firestore (so changes persist)
      if (window.EBTR_FETCH_MY_PROFILE) window.EBTR_FETCH_MY_PROFILE(v.email).then(function (p) {
        if (p) setMe(function (m) { return Object.assign({}, m, { title: p.title != null ? p.title : m.title, bio: p.bio != null ? p.bio : m.bio, badges: p.badges || m.badges, portraitUrl: p.portraitUrl || m.portraitUrl }); });
      }).catch(function () {});
    });
  }, []);

  const signIn = () => {
    if (LIVE) { window.EBTR_AUTH.google().catch(function (e) { alert(e && e.message ? e.message : "Sign-in failed"); }); return; }
    try { localStorage.setItem(PORTAL_LS, "1"); } catch (e) {} setAuthed(true); setRoute({ name: "dashboard" });
  };
  const sendLink = (email) => {
    if (LIVE) { return window.EBTR_AUTH.sendLink(email).then(function () { alert("Sign-in link sent to " + email + ". Open it on this device to finish."); }).catch(function (e) { alert(e && e.message ? e.message : "Could not send link"); }); }
    try { localStorage.setItem(PORTAL_LS, "1"); } catch (e) {} setAuthed(true);
  };
  const signOut = () => { if (LIVE) { window.EBTR_AUTH.signOut(); return; } try { localStorage.removeItem(PORTAL_LS); } catch (e) {} setAuthed(false); };
  const goDash = () => { setRoute({ name: "dashboard" }); window.scrollTo(0, 0); };
  const submitArticle = (article) => {
    if (!LIVE) { alert("Submitted (demo mode — not saved to the database)."); setConfirm(true); return; }
    if (!window.EBTR_SAVE_SUBMISSION) { alert("Submit function missing — old build deployed. Re-deploy the latest files."); return; }
    if (!article || !article.authorEmail) { alert("No email on your session — sign out and sign in with Google again."); return; }
    window.EBTR_SAVE_SUBMISSION(article)
      .then(function () { setConfirm(true); })
      .catch(function (e) { alert("Submission failed to save: " + (e && e.message ? e.message : e)); });
  };
  const openSub = (id) => { setRoute({ name: "detail", id }); window.scrollTo(0, 0); };
  const newSub = (draft) => { setRoute({ name: "submit", draft: draft || null }); window.scrollTo(0, 0); };

  if (LIVE && authState === "checking") return <div style={{ minHeight: "100vh", background: "var(--ebt-ink)" }} />;
  if (!authed) return <PAuth onContinue={signIn} onSendLink={sendLink} live={LIVE} />;

  return (
    <div style={{ minHeight: "100vh", background: "var(--ebt-ink)", "--ebtr-display": "var(--font-ui)" }}>
      <PHeader me={me} onHome={goDash} onNew={() => newSub(null)} onGuide={() => setGuideOpen(true)} onProfile={() => { setRoute({ name: "profile" }); window.scrollTo(0, 0); }} onSignOut={signOut} />

      {route.name === "dashboard" && <PDashboard onOpen={openSub} onNew={() => newSub(null)} me={me} />}
      {route.name === "detail" && <PDetail id={route.id} onBack={goDash} onResubmit={(s) => newSub(s)} />}
      {route.name === "submit" && <PSubmit draft={route.draft} me={me} onCancel={goDash} onGuide={() => setGuideOpen(true)} onSubmitted={submitArticle} />}
      {route.name === "profile" && <PProfile me={me} onSave={saveProfile} onBack={goDash} />}

      <PGuideDrawer open={guideOpen} onClose={() => setGuideOpen(false)} />

      {confirm && (
        <PModal title="Submission received" subtitle="It's in the editors' queue. We screen against the same quality bar you just cleared and reply within 14 days — you'll track every status change right here on your dashboard." onClose={() => { setConfirm(false); goDash(); }}>
          <PBtn variant="primary" size="lg" icon="none" onClick={() => { setConfirm(false); goDash(); }}>Back to dashboard</PBtn>
        </PModal>
      )}
    </div>
  );
}

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