// Swivy — app entry

const { useState: useStateA, useEffect: useEffectA, useCallback: useCallbackA } = React;

const App = () => {
  const [tweaks, setTweaks] = useStateA(window.__SWIVY_TWEAKS__);
  const [route, setRoute] = useStateA(() => localStorage.getItem("swivy.route") || "handoff");
  const [env, setEnv] = useStateA(() => localStorage.getItem("swivy.env") || "staging");
  const [project, setProject] = useStateA(PROJECTS[0]);
  const [modal, setModal] = useStateA(null);
  const [tweaksOpen, setTweaksOpen] = useStateA(false);

  useEffectA(() => { localStorage.setItem("swivy.route", route); }, [route]);
  useEffectA(() => { localStorage.setItem("swivy.env", env); }, [env]);

  const setTweak = useCallbackA((k, v) => {
    setTweaks(prev => {
      const next = { ...prev, [k]: v };
      window.parent?.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
      return next;
    });
  }, []);

  // Edit mode protocol
  useEffectA(() => {
    const handler = (e) => {
      if (!e?.data?.type) return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent?.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  // Theme + density application
  useEffectA(() => {
    const r = document.documentElement;
    r.setAttribute("data-theme", tweaks.theme);
    r.setAttribute("data-type", tweaks.typeDirection);
    r.setAttribute("data-density", tweaks.density);
    r.style.setProperty("--env-current", `var(--env-${env})`);
  }, [tweaks, env]);

  const openModal = useCallbackA((kind) => setModal(kind), []);
  const closeModal = useCallbackA(() => setModal(null), []);

  const Screen = () => {
    switch (route) {
      case "overview": return <OverviewScreen setRoute={setRoute} openModal={openModal}/>;
      case "handoff": return <HandoffScreen setRoute={setRoute} openModal={openModal} tweaks={tweaks}/>;
      case "keys": return <KeysScreen openModal={openModal} env={env}/>;
      case "oidc": return <OidcScreen openModal={openModal} tweaks={tweaks}/>;
      case "wallets": return <WalletsScreen openModal={openModal}/>;
      case "signing": return <SigningScreen openModal={openModal}/>;
      case "policies": return <PoliciesScreen/>;
      case "audit": return <AuditScreen/>;
      case "webhooks":
      case "chains":
      case "members":
      case "settings":
      default:
        return <ComingSoon route={route} tweaks={tweaks}/>;
    }
  };

  const showRail = tweaks.envSwitcherStyle === "rail-and-pill";

  return (
    <div className="app" data-screen-label={`Swivy · ${route}`}>
      {showRail && <div className="env-rail"/>}
      <Sidebar route={route} setRoute={setRoute}/>
      <main className="main">
        <Topbar route={route} env={env} setEnv={setEnv} project={project} setProject={setProject} openCmd={() => {}}/>
        <div className="content">
          <Screen/>
        </div>
      </main>

      {modal === "sign" && <SigningModal onClose={closeModal} style={tweaks.signingModalStyle}/>}
      {modal === "rotate" && <RotateModal onClose={closeModal} pattern={tweaks.dangerousActionPattern}/>}
      {modal === "newkey" && <NewKeyModal onClose={closeModal}/>}

      {tweaksOpen && <TweaksPanel tweaks={tweaks} setTweak={setTweak} onClose={() => setTweaksOpen(false)}/>}
    </div>
  );
};

const ComingSoon = ({ route, tweaks }) => (
  <>
    <div className="page-header">
      <div>
        <h1 className="page-title" style={{ textTransform: "capitalize" }}>{route}</h1>
        <p className="page-sub">This surface is scaffolded but not part of the hero flow. Below is the empty-state treatment used across new-project installs.</p>
      </div>
    </div>
    <Card>
      <Empty
        illus={tweaks.emptyStateStyle}
        title={`No ${route} yet`}
        desc="Swivy teaches the next step instead of showing an empty table. Click below to scaffold a starter — you can always delete it later."
        actions={<>
          <Btn variant="secondary" icon={<IBook size={13}/>}>Read guide</Btn>
          <Btn variant="primary" icon={<IPlus size={13}/>}>Scaffold</Btn>
        </>}
      />
    </Card>
  </>
);

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