// Customer portal (support.usenudge.app). Entry gate — ticket # + work email
// to follow tickets, or just an email to report something new — then a
// workspace scoped to that person. Admins use the separate admin surface
// (admin.html / adminsupport.usenudge.app), not a toggle here.
const { useState: useStateApp, useEffect: useEffectApp } = React;

function NudgeToast({ toast, onDismiss }) {
  useEffectApp(() => {
    if (!toast) return;
    const t = setTimeout(onDismiss, 3800);
    return () => clearTimeout(t);
  }, [toast && toast.id, onDismiss]);
  if (!toast) return null;
  return (
    <div key={toast.id} className="nudge-toast" role="status" aria-live="polite">
      <span className="nudge-toast-dot" /><span>{toast.msg}</span>
    </div>
  );
}

function BrandMark() {
  return (
    <div className="brand-lockup">
      <span className="brand-dots"><i></i><i></i><i></i></span>
      Nudge <span className="brand-sub">Support</span>
    </div>
  );
}

// The entry screen: track existing tickets, or start a new report.
function CustomerEntry({ onEnter }) {
  const [tab, setTab] = useStateApp("track");      // track | report
  const [email, setEmail] = useStateApp("");
  const [ticket, setTicket] = useStateApp("");
  const [err, setErr] = useStateApp("");
  const [busy, setBusy] = useStateApp(false);

  const validEmail = (e) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim());

  async function track(e) {
    e.preventDefault(); setErr("");
    if (!validEmail(email)) return setErr("Enter your work email.");
    if (!ticket.trim()) return setErr("Enter your ticket number (e.g. SUP-1042).");
    setBusy(true);
    const res = await window.NS.session.verify(ticket, email);
    setBusy(false);
    if (!res.ok) {
      return setErr(res.reason === "unauthorized"
        ? "Access is restricted for this site."
        : "We couldn't find that ticket for that email. Double-check both, or report a new issue.");
    }
    window.NS.session.set({ email: email.trim().toLowerCase() });
    onEnter("tickets");
  }

  function report(e) {
    e.preventDefault(); setErr("");
    if (!validEmail(email)) return setErr("Enter your work email so we can follow up.");
    window.NS.session.set({ email: email.trim().toLowerCase() });
    onEnter("chat");
  }

  return (
    <div className="gate">
      <div className="gate-card card">
        <BrandMark />
        <h1 className="gate-title">{tab === "track" ? "Track your support tickets" : "Report an issue"}</h1>
        <p className="gate-sub">
          {tab === "track"
            ? "Enter your ticket number and the work email you reported with."
            : "Tell us your work email and we'll take it from there — no account needed."}
        </p>

        <div className="seg gate-seg" role="tablist">
          <button className={tab === "track" ? "is-active" : ""} onClick={() => { setTab("track"); setErr(""); }}>Track tickets</button>
          <button className={tab === "report" ? "is-active" : ""} onClick={() => { setTab("report"); setErr(""); }}>Report an issue</button>
        </div>

        <form onSubmit={tab === "track" ? track : report} className="gate-form">
          <label className="gate-field">
            <span>Work email</span>
            <input type="email" autoComplete="email" placeholder="you@company.com"
              value={email} onChange={(e) => setEmail(e.target.value)} />
          </label>
          {tab === "track" && (
            <label className="gate-field">
              <span>Ticket number</span>
              <input placeholder="SUP-1042" value={ticket}
                onChange={(e) => setTicket(e.target.value)} />
            </label>
          )}
          {err && <div className="gate-err">{err}</div>}
          <button type="submit" className="btn btn-primary gate-submit" disabled={busy}>
            {busy ? "Checking…" : tab === "track" ? "View my tickets" : "Start a report"}
          </button>
        </form>

        <p className="gate-switch">
          {tab === "track"
            ? <>No ticket yet? <a onClick={() => { setTab("report"); setErr(""); }}>Report a new issue</a></>
            : <>Already have a ticket? <a onClick={() => { setTab("track"); setErr(""); }}>Track it here</a></>}
        </p>
      </div>
    </div>
  );
}

function App() {
  const [session, setSession] = useStateApp(() => window.NS.session.get());
  const [view, setView] = useStateApp("tickets");   // tickets | chat
  const [toast, setToast] = useStateApp(null);
  const [theme, setTheme] = useStateApp(() => document.documentElement.getAttribute("data-theme") || "light");

  useEffectApp(() => {
    window.NS.seedIfEmpty();
    window.fireToast = (msg) => setToast({ id: Date.now() + Math.random(), msg });
    return () => { delete window.fireToast; };
  }, []);
  useEffectApp(() => { document.documentElement.setAttribute("data-theme", theme); }, [theme]);

  const themeBtn = (
    <button className="icon-btn" title="Toggle theme" onClick={() => setTheme((t) => (t === "dark" ? "light" : "dark"))}>
      {theme === "dark" ? "☀" : "☾"}
    </button>
  );

  if (!session) {
    return (
      <React.Fragment>
        <header className="topbar"><BrandMark /><div className="topbar-spacer" />{themeBtn}</header>
        <CustomerEntry onEnter={(v) => { setSession(window.NS.session.get()); setView(v); }} />
        <NudgeToast toast={toast} onDismiss={() => setToast(null)} />
      </React.Fragment>
    );
  }

  const identity = window.NS.session.identity();
  const signOut = () => { window.NS.session.clear(); setSession(null); setView("tickets"); };

  return (
    <div className="app">
      <header className="topbar">
        <BrandMark />
        <div className="topbar-spacer" />
        <div className="seg" role="tablist" aria-label="View">
          <button className={view === "tickets" ? "is-active" : ""} onClick={() => setView("tickets")}>My tickets</button>
          <button className={view === "chat" ? "is-active" : ""} onClick={() => setView("chat")}>Report a bug</button>
        </div>
        <span className="who-chip" title={identity.email}>{identity.email}</span>
        <button className="btn btn-ghost btn-sm" onClick={signOut}>Sign out</button>
        {themeBtn}
      </header>

      <main className="main">
        {view === "tickets" && <CustomerDashboard onNewReport={() => setView("chat")} />}
        {view === "chat" && (
          <div style={{ maxWidth: 560, margin: "0 auto" }}>
            <div className="page-head" style={{ textAlign: "center" }}>
              <div className="eyebrow">Report a bug</div>
              <h1 className="page-title">What's going wrong?</h1>
              <p className="page-sub" style={{ marginInline: "auto" }}>Just describe it in your own words — I'll take it from there.</p>
            </div>
            <div className="card" style={{ padding: 0, height: 560, overflow: "hidden" }}>
              <AgentChat />
            </div>
          </div>
        )}
      </main>

      <NudgeToast toast={toast} onDismiss={() => setToast(null)} />
    </div>
  );
}

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