// App shell — ties everything together
const { motion: M, AnimatePresence: AP } = window;
const { Sidebar: AppSidebar, Btn: AppBtn, LoopMark: AppLogo, Avatar: AppAvatar, Pill: AppPill } = window.UI;

function Login({ onLogin }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    if (!password) return;
    setBusy(true); setErr(null);
    const r = await window.LoopData.login(email, password);
    setBusy(false);
    if (r && r.agent) onLogin(r.agent);
    else setErr(r && r.error === "invalid_credentials" ? "Wrong email or password." : "Could not sign in. Is the backend running?");
  };
  const inp = "w-full h-11 px-3 rounded-xl bg-white/[0.03] border border-white/[0.07] focus:border-lime/60 outline-none text-[13.5px] text-white/90 placeholder:text-white/30";
  return (
    <div className="h-full grid place-items-center bg-ink-950">
      <div className="w-[360px] max-w-[92vw] glass-strong rounded-2xl p-6">
        <div className="flex items-center gap-2.5 mb-5"><AppLogo size={30}/><div className="text-white/95 font-semibold text-[16px]">Loop</div></div>
        <div className="text-[15px] text-white/90 font-medium mb-4">Sign in to your console</div>
        <div className="space-y-2.5">
          <input className={inp} value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@company.com"/>
          <input className={inp} type="password" value={password} onChange={e=>setPassword(e.target.value)} onKeyDown={e=>{ if(e.key==="Enter") submit(); }} placeholder="Password"/>
          {err && <div className="text-rose-300 text-[12px]">{err}</div>}
          <button onClick={submit} disabled={busy||!password} className="btn-lime w-full h-11 rounded-xl font-semibold disabled:opacity-40">{busy?"Signing in…":"Sign in"}</button>
        </div>
      </div>
    </div>
  );
}

function AlertControls() {
  if (!window.LoopNotify) return null;
  const [sound, setSound] = React.useState(window.LoopNotify.get("sound"));
  const [voice, setVoice] = React.useState(window.LoopNotify.get("voice"));
  const chip = (on) => `text-[10.5px] px-2 py-0.5 rounded-full border transition ${on ? "bg-lime/10 text-lime border-lime/30" : "bg-white/[0.05] text-white/45 border-white/[0.1]"}`;
  return (
    <div className="flex items-center gap-1.5">
      <button className={chip(sound)} title="Message sound" onClick={() => { const v = !sound; setSound(v); window.LoopNotify.set("sound", v); window.LoopNotify.unlock(); }}>🔔 Sound</button>
      <button className={chip(voice)} title="Spoken AI alert" onClick={() => { const v = !voice; setVoice(v); window.LoopNotify.set("voice", v); window.LoopNotify.unlock(); }}>🗣 Voice</button>
      <button className="text-[10.5px] px-2 py-0.5 rounded-full border bg-white/[0.05] text-white/55 border-white/[0.1] hover:text-white/80" title="Test alert" onClick={() => window.LoopNotify.test()}>Test</button>
    </div>
  );
}

function App() {
  // mode: "marketing" | "app"
  const [mode, setMode] = React.useState("marketing");
  // marketing page: home | sites | pricing | customers
  const [marketingPage, setMarketingPage] = React.useState("home");
  const [active, setActive] = React.useState("overview");
  const [widgetOpen, setWidgetOpen] = React.useState(false);
  const [widgetState, setWidgetState] = React.useState("welcome");
  const [dataReady, setDataReady] = React.useState(false);
  const [dataMode, setDataMode] = React.useState("mock");
  const [authAgent, setAuthAgent] = React.useState(null);
  const [authChecked, setAuthChecked] = React.useState(false);
  const [navOpen, setNavOpen] = React.useState(false); // mobile sidebar drawer

  React.useEffect(() => {
    if (window.LoopData) {
      window.LoopData.bootstrap().then((m) => { setDataMode(m); setDataReady(true); });
    } else { setDataReady(true); }
    if (window.LoopData && window.LoopData.me) {
      Promise.resolve(window.LoopData.me()).then((a) => { setAuthAgent(a || null); setAuthChecked(true); });
    } else { setAuthChecked(true); }
  }, []);

  React.useEffect(() => {
    const hash = window.location.hash.replace("#", "");
    if (hash === "app") setMode("app");
    if (hash.startsWith("app/")) {
      setMode("app");
      setActive(hash.split("/")[1]);
    }
    if (["sites","pricing","customers"].includes(hash)) {
      setMarketingPage(hash);
    }
  }, []);

  // Alert the CSR (sound + spoken brand/urgency) on new inbound customer
  // messages for sites this agent handles.
  React.useEffect(() => {
    if (!authAgent || !window.LoopData || !window.LoopData.onInbound) return;
    return window.LoopData.onInbound((m) => {
      if (authAgent.role !== "Admin" && Array.isArray(authAgent.websites) && !authAgent.websites.includes(m.site)) return;
      const site = (window.Mock.websites || []).find((w) => w.id === m.site);
      if (window.LoopNotify) window.LoopNotify.alert({
        brand: (site && site.name) || m.site,
        urgent: !!(m.humanRequested || m.waiting),
        visitor: m.visitor, text: m.text, conversationId: m.conversationId,
      });
    });
  }, [authAgent]);

  const goTo = (id) => setActive(id);
  const onLogin = async (agent) => {
    setAuthAgent(agent);
    if (window.LoopData) { if (window.LoopData.setCurrentAgent) window.LoopData.setCurrentAgent(agent.id); const m = await window.LoopData.bootstrap(); setDataMode(m); }
  };
  const onLogout = () => { if (window.LoopData && window.LoopData.logout) window.LoopData.logout(); setAuthAgent(null); setActive("overview"); };
  const enterApp = () => { setMode("app"); window.location.hash = "app"; };
  const exitApp = () => { setMode("marketing"); setMarketingPage("home"); window.location.hash = ""; };
  const navMarketing = (page) => {
    if (page === "changelog") return; // not built — no-op
    setMode("marketing");
    setMarketingPage(page);
    window.location.hash = page === "home" ? "" : page;
    window.scrollTo({ top: 0 });
    // Also reset internal scroll of marketing container
    setTimeout(() => {
      const el = document.querySelector("#root > div");
      if (el && el.scrollTo) el.scrollTo({ top: 0 });
    }, 0);
  };

  if (mode === "marketing") {
    return (
      <>
        {marketingPage === "home" && <window.Landing onLaunch={enterApp} onNav={navMarketing}/>}
        {marketingPage === "sites" && <window.Sites onLaunch={enterApp} onNav={navMarketing}/>}
        {marketingPage === "pricing" && <window.Pricing onLaunch={enterApp} onNav={navMarketing}/>}
        {marketingPage === "customers" && <window.Customers onLaunch={enterApp} onNav={navMarketing}/>}
      </>
    );
  }

  if (mode === "app" && dataReady && authChecked && !authAgent) {
    return <Login onLogin={onLogin} />;
  }

  if (!dataReady || !authChecked) {
    return (
      <div className="h-full grid place-items-center bg-ink-950 text-white/40 text-[13px]">
        <span>Loading workspace...</span>
      </div>
    );
  }

  return (
    <div className="h-full flex bg-ink-950">
      <AppSidebar active={active} onChange={goTo} onOpenLanding={exitApp} role={authAgent.role} agent={authAgent} onLogout={onLogout} open={navOpen} onClose={() => setNavOpen(false)}/>
      {navOpen && <div onClick={() => setNavOpen(false)} className="fixed inset-0 z-50 bg-black/50 md:hidden" />}
      <div className="flex-1 flex flex-col min-w-0 relative">
        <button onClick={() => setNavOpen(true)} aria-label="Menu" className="md:hidden absolute top-2.5 left-3 z-40 h-9 w-9 grid place-items-center rounded-xl bg-white/[0.05] border border-white/[0.08] text-white/75 hover:text-white"><Icon.Menu size={18}/></button>
        <div className="absolute top-3 right-4 z-50 flex items-center gap-2">
          <AlertControls />
          <div className={`text-[10.5px] px-2 py-0.5 rounded-full border ${dataMode === "live" ? "bg-lime/10 text-lime border-lime/30" : "bg-white/[0.05] text-white/55 border-white/[0.1]"}`}>
            {dataMode === "live" ? "Live" : "Demo data"}
          </div>
        </div>
        <AP mode="wait">
          <M.div
            key={active}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            transition={{ duration: 0.18 }}
            className="flex-1 flex flex-col min-h-0"
          >
            {active === "overview" && <window.Dashboard onGoTo={goTo} authAgent={authAgent}/>}
            {active === "conversations" && <window.Conversations authAgent={authAgent}/>}
            {active === "messenger" && <window.Conversations authAgent={authAgent} defaultChannel="messenger"/>}
            {active === "websites" && <window.Websites/>}
            {active === "agents" && <window.Agents/>}
            {active === "canned" && <window.Canned/>}
            {active === "analytics" && <window.Analytics/>}
            {active === "settings" && <window.Settings/>}
            {active === "admin" && (["Admin", "Manager"].includes(authAgent.role) ? <window.Admin authAgent={authAgent}/> : <div className="p-10 text-white/50 text-sm">Admins only.</div>)}
          </M.div>
        </AP>

        {/* Floating widget toggle on app screens */}
        <button
          onClick={() => { setWidgetOpen(o => !o); setWidgetState("welcome"); }}
          className="fixed bottom-6 right-6 z-40 grid place-items-center w-12 h-12 rounded-full glass-strong text-white/70 hover:text-white"
          title="Preview live widget"
        >
          <Icon.Eye size={18}/>
        </button>

        <div className="fixed bottom-20 right-6 z-40">
          <AP>
            {widgetOpen && (
              <window.ChatWidget
                key="prev-widget"
                initialState={widgetState}
                onClose={() => setWidgetOpen(false)}
              />
            )}
          </AP>
        </div>
      </div>
    </div>
  );
}

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