/* Yappari Dashboard — App root + role-based router */
const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const [route, setRoute]       = useStateApp({ name: "overview" });
  const [user, setUser]         = useStateApp(() => {
    try { return JSON.parse(localStorage.getItem("yappari_user") || "null"); } catch { return null; }
  });
  const [machines, setMachines] = useStateApp([]);
  const [users, setUsers]       = useStateApp([]);
  const [invoices, setInvoices] = useStateApp([]);
  const [toastState, setToast]  = useStateApp(null);
  const [loading, setLoading]   = useStateApp(true);
  const [loadErr, setLoadErr]   = useStateApp(null);

  // Initial load from Supabase
  useEffectApp(() => {
    loadInitialData()
      .then(({ users, machines, invoices }) => {
        setUsers([...users]);
        setMachines([...machines]);
        setInvoices([...invoices]);
        setLoading(false);
      })
      .catch(err => {
        console.error("loadInitialData failed:", err);
        setLoadErr(err.message || String(err));
        setLoading(false);
      });
  }, []);

  useEffectApp(() => {
    if (user) localStorage.setItem("yappari_user", JSON.stringify(user));
    else localStorage.removeItem("yappari_user");
  }, [user]);

  const navigate = (r) => { setRoute(r); window.scrollTo({ top: 0, behavior: "instant" }); };
  const toast    = (msg, tone = "info") => setToast({ msg, tone });

  const login  = (u) => { setUser(u); navigate({ name: "overview" }); toast(`Selamat datang, ${u.name.split(" ")[0]}!`, "success"); };
  const logout = () => { setUser(null); navigate({ name: "overview" }); };

  // client sees only their machines
  const clientMachines = user?.role === "client"
    ? machines.filter(m => m.clientId === user.id)
    : machines;

  const ctx = {
    user,
    isAdmin: user?.role === "admin",
    machines: clientMachines,
    allMachines: machines,
    setMachines,
    users,
    setUsers,
    invoices,
    setInvoices,
    route, navigate,
    login, logout, toast,
  };

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-[#FAF6EF]">
      <div className="text-center">
        <div className="inline-block w-12 h-12 border-4 border-[#FF2D55] border-t-transparent rounded-full animate-spin"></div>
        <div className="font-display text-xl uppercase text-[#1A1A1A] mt-4">Memuat data...</div>
        <div className="text-xs text-stone-500 mt-1 font-jp">読み込み中</div>
      </div>
    </div>
  );

  if (loadErr) return (
    <div className="min-h-screen flex items-center justify-center bg-[#FAF6EF] p-6">
      <div className="max-w-md bg-white border border-rose-200 rounded-2xl p-6 shadow-xl">
        <div className="text-rose-600 font-display text-2xl uppercase">Gagal Memuat Data</div>
        <div className="text-sm text-stone-600 mt-2">{loadErr}</div>
        <div className="mt-4 text-xs text-stone-500 bg-stone-50 rounded-lg p-3 border border-stone-200">
          Pastikan migration SQL sudah di-run di Supabase SQL Editor. File: <code className="font-mono">migrations/001_initial_schema.sql</code>
        </div>
        <button onClick={() => window.location.reload()} className="mt-4 px-5 py-2.5 rounded-full bg-[#FF2D55] text-white font-semibold text-sm hover:bg-[#E61243]">
          Coba Lagi
        </button>
      </div>
    </div>
  );

  if (!user) return (
    <AppCtx.Provider value={ctx}>
      <LoginView />
      <Toast toast={toastState} onClose={() => setToast(null)} />
    </AppCtx.Provider>
  );

  return (
    <AppCtx.Provider value={ctx}>
      <div className="flex bg-[#FAF6EF] min-h-screen text-[#1A1A1A] pb-16 md:pb-0">
        <Sidebar />
        <div className="flex-1 min-w-0 flex flex-col">
          <TopBar />
          <main className="flex-1">
            {/* ── Shared ── */}
            {route.name === "overview"         && <OverviewView />}
            {route.name === "profile"          && <ProfileView />}

            {/* ── Client ── */}
            {route.name === "machines"         && <MachinesView />}
            {route.name === "machine-detail"   && <MachineDetailView />}
            {route.name === "machine-renew"    && <CheckoutView />}
            {route.name === "payment-success"  && <PaymentSuccessView />}
            {route.name === "payment-failed"   && <PaymentFailedView />}

            {/* ── Admin ── */}
            {route.name === "admin-clients"    && <AdminClientsView />}
            {route.name === "admin-machines"   && <AdminMachinesView />}
            {route.name === "admin-billing"    && <AdminBillingView />}
            {route.name === "admin-invoices"   && <AdminInvoicesView />}
            {route.name === "admin-telemetron" && <TelemetronSettingsView />}
            {route.name === "admin-settings"   && <AdminSettingsView />}
          </main>
          <footer className="px-5 md:px-8 py-5 text-[11px] text-stone-400 flex flex-wrap items-center gap-2 border-t border-stone-200 bg-white">
            <span>© 2026 Yappari! Vending Machine</span>
            <span>·</span>
            <span>PT. INDIE KREASI GROUP</span>
            <span className="ml-auto">Bantuan: <a href="https://wa.me/628976046500" target="_blank" rel="noopener" className="text-[#FF2D55] font-semibold">0897 604 6500</a></span>
          </footer>
        </div>
        <MobileNav />
      </div>
      <Toast toast={toastState} onClose={() => setToast(null)} />
    </AppCtx.Provider>
  );
}

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