// Authenticated admin shell for the local demo.

const ADMIN_DEMO = { phone: "091234567890", password: "Kotleto1405" };

function AdminLogin({ onSuccess, onExit, accent }) {
  const { lang } = useLang();
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const submit = event => {
    event.preventDefault();
    const normalizedPhone = toEn(phone).replace(/\D/g, "");
    if (normalizedPhone === ADMIN_DEMO.phone && password === ADMIN_DEMO.password) {
      sessionStorage.setItem("kotleto-admin-auth", "1");
      setError("");
      onSuccess();
      notify(lang === "fa" ? "ورود مدیر موفق بود" : "Admin login successful");
      return;
    }
    setError(lang === "fa" ? "شماره موبایل یا رمز عبور درست نیست." : "Phone number or password is incorrect.");
  };
  return <main style={{ minHeight: "100dvh", background: "#0F0B08", color: "var(--paper)", display: "grid", placeItems: "center", padding: 18, position: "relative", overflow: "hidden" }}>
    <div aria-hidden="true" style={{ position: "absolute", width: 420, height: 420, borderRadius: 999, background: accent, filter: "blur(130px)", opacity: .13, top: -180, insetInlineEnd: -120 }} />
    <section style={{ width: "min(460px, 100%)", background: "#17110D", border: "1px solid rgba(255,244,226,.13)", borderRadius: 26, padding: "clamp(22px,5vw,34px)", boxShadow: "0 36px 100px rgba(0,0,0,.5)", position: "relative" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 14 }}>
        <KotletoMark light scale={.92} />
        <button type="button" onClick={onExit} className="btn btn-ghost btn-sm" style={{ color: "var(--paper)", borderColor: "rgba(255,244,226,.18)" }}>{lang === "fa" ? "بازگشت" : "Back"}</button>
      </div>
      <div style={{ marginTop: 28 }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 7, color: accent, fontSize: 12, fontWeight: 800 }}><span style={{ width: 7, height: 7, borderRadius: 99, background: accent }} />{lang === "fa" ? "ورود امن نسخه دمو" : "Secure demo access"}</div>
        <h1 className="display" style={{ margin: "8px 0 6px", fontSize: "clamp(30px,7vw,43px)" }}>{lang === "fa" ? "ورود مدیر" : "Admin login"}</h1>
        <p style={{ color: "rgba(255,244,226,.55)", lineHeight: 1.8, fontSize: 13, margin: 0 }}>{lang === "fa" ? "برای مدیریت سفارش‌ها، منو و تنظیمات وارد شوید." : "Sign in to manage orders, menu and settings."}</p>
      </div>
      <form onSubmit={submit} style={{ display: "grid", gap: 14, marginTop: 24 }}>
        <label style={{ display: "grid", gap: 7 }}><span style={{ fontSize: 12, color: "rgba(255,244,226,.65)" }}>{lang === "fa" ? "شماره موبایل مدیر" : "Admin phone"}</span><input autoFocus inputMode="numeric" autoComplete="username" dir="ltr" value={phone} onChange={event => setPhone(event.target.value)} placeholder={lang === "fa" ? "شماره موبایل مدیر را وارد کنید" : "Enter admin phone"} style={{ ...ADMIN_INPUT_STYLE, padding: "13px 14px" }} /></label>
        <label style={{ display: "grid", gap: 7 }}><span style={{ fontSize: 12, color: "rgba(255,244,226,.65)" }}>{lang === "fa" ? "رمز عبور" : "Password"}</span><div style={{ position: "relative" }}><input type={showPassword ? "text" : "password"} autoComplete="current-password" dir="ltr" value={password} onChange={event => setPassword(event.target.value)} placeholder="••••••••" style={{ ...ADMIN_INPUT_STYLE, padding: "13px 14px", paddingInlineEnd: 72, direction: lang === "fa" ? "rtl" : "ltr" }} /><button type="button" onClick={() => setShowPassword(value => !value)} style={{ position: "absolute", insetInlineEnd: 8, top: "50%", transform: "translateY(-50%)", color: "rgba(255,244,226,.6)", fontSize: 11, fontWeight: 700, padding: "7px 8px" }}>{showPassword ? (lang === "fa" ? "مخفی" : "Hide") : (lang === "fa" ? "نمایش" : "Show")}</button></div></label>
        {error && <div role="alert" style={{ color: "#FF8C7C", background: "rgba(255,108,90,.09)", border: "1px solid rgba(255,108,90,.2)", borderRadius: 11, padding: "10px 12px", fontSize: 12 }}>{error}</div>}
        <button className="btn btn-primary btn-lg" type="submit" style={{ width: "100%", justifyContent: "center" }}>{lang === "fa" ? "ورود به پنل" : "Sign in"} <Ico.Arrow /></button>
      </form>
    </section>
  </main>;
}

function AdminApp({ onExit, accent = "#D9461E" }) {
  const { lang, setLang } = useLang();
  const [authenticated, setAuthenticated] = useState(() => sessionStorage.getItem("kotleto-admin-auth") === "1");
  const [tab, setTab] = useState("overview");
  const [search, setSearch] = useState("");
  const [searchDraft, setSearchDraft] = useState("");
  const [notifOpen, setNotifOpen] = useState(false);
  const [profileOpen, setProfileOpen] = useState(false);
  const [notifs, setNotifs] = useState(() => LocalDB.get("adminNotifications", NOTIFICATIONS));
  useEffect(() => { LocalDB.set("adminNotifications", notifs); }, [notifs]);
  if (!authenticated) return <AdminLogin accent={accent} onExit={onExit} onSuccess={() => setAuthenticated(true)} />;

  const tabs = [
    { id: "overview", fa: "داشبورد", en: "Overview", ic: <Ico.Chart /> },
    { id: "orders", fa: "سفارش‌ها", en: "Orders", ic: <Ico.Bag /> },
    { id: "menu", fa: "منو", en: "Menu", ic: <Ico.Sparkle /> },
    { id: "customers", fa: "مشتری‌ها", en: "Customers", ic: <Ico.Heart /> },
    { id: "staff", fa: "کارمندان", en: "Staff", ic: <Ico.User /> },
    { id: "reports", fa: "گزارش‌ها", en: "Reports", ic: <Ico.Chart /> },
    { id: "settings", fa: "تنظیمات", en: "Settings", ic: <Ico.Cog /> },
  ];
  const navigate = id => { setTab(id); if (id !== "orders") setSearch(""); };
  const logout = () => {
    sessionStorage.removeItem("kotleto-admin-auth");
    setAuthenticated(false);
    setProfileOpen(false);
    notify(lang === "fa" ? "از پنل خارج شدید" : "Signed out");
  };
  const doSearch = event => {
    event.preventDefault();
    const query = searchDraft.trim();
    if (!query) return;
    setSearch(query); setTab("orders");
  };
  const unread = notifs.filter(item => item.unread).length;
  const currentTab = tabs.find(item => item.id === tab);

  return <div className="grid grid-admin" style={{ minHeight: "100vh", background: "#0F0B08", color: "var(--paper)", fontFamily: "var(--fa)" }}>
    <AdminControlsStyles />
    <aside className="admin-sidebar" style={{ background: "#070504", borderInlineEnd: "1px solid rgba(255,244,226,.08)", padding: "22px 17px", display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ padding: "0 6px" }}><KotletoMark light scale={.82} /></div>
      <div style={{ height: 1, background: "rgba(255,244,226,.08)" }} />
      <nav className="admin-nav" aria-label={lang === "fa" ? "منوی مدیریت" : "Admin navigation"} style={{ display: "flex", flexDirection: "column", gap: 3 }}>
        {tabs.map(item => <button key={item.id} onClick={() => navigate(item.id)} aria-current={tab === item.id ? "page" : undefined} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", borderRadius: 11, background: tab === item.id ? accent : "transparent", color: tab === item.id ? "#fff" : "rgba(255,244,226,.68)", fontWeight: 700, fontSize: 13, whiteSpace: "nowrap" }}>{item.ic}{item[lang]}</button>)}
      </nav>
      <div className="hide-mobile-md" style={{ marginTop: "auto", display: "grid", gap: 10 }}>
        <button onClick={onExit} className="btn btn-ghost" style={{ color: "rgba(255,244,226,.75)", borderColor: "rgba(255,244,226,.2)" }}>{lang === "fa" ? "بازگشت به سایت" : "Back to website"}</button>
      </div>
    </aside>
    <main className="admin-main" style={{ padding: "24px 28px", overflow: "hidden" }}>
      <header style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, flexWrap: "wrap", position: "relative", zIndex: 8 }}>
        <div><div style={{ fontSize: 11, color: "rgba(255,244,226,.5)", letterSpacing: ".16em", textTransform: "uppercase", fontWeight: 800 }}>{lang === "fa" ? "مدیریت · کتلتُ" : "OPERATIONS · Kotleto"}</div><h1 className="display" style={{ margin: "5px 0 0", fontSize: "clamp(27px,4vw,38px)" }}>{currentTab?.[lang]}</h1></div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <form className="hide-mobile-md" onSubmit={doSearch} style={{ position: "relative" }}><Ico.Search style={{ position: "absolute", insetInlineStart: 12, top: "50%", transform: "translateY(-50%)", opacity: .5 }} /><input value={searchDraft} onChange={event => setSearchDraft(event.target.value)} placeholder={lang === "fa" ? "جستجوی سفارش یا مشتری..." : "Search order or customer..."} style={{ ...ADMIN_INPUT_STYLE, width: 270, paddingInlineStart: 38 }} /></form>
          <button onClick={() => setLang(lang === "fa" ? "en" : "fa")} className="btn btn-ghost btn-sm" style={{ color: "var(--paper)", borderColor: "rgba(255,244,226,.16)" }}>{lang === "fa" ? "EN" : "فا"}</button>
          <button className="show-mobile btn btn-ghost btn-sm" onClick={onExit} style={{ color: "var(--paper)", borderColor: "rgba(255,244,226,.16)" }}>{lang === "fa" ? "سایت" : "Site"}</button>
          <div style={{ position: "relative" }}>
            <button onClick={() => { setNotifOpen(value => !value); setProfileOpen(false); }} aria-label={lang === "fa" ? "اعلان‌ها" : "Notifications"} style={{ width: 42, height: 42, display: "grid", placeItems: "center", borderRadius: 12, color: "var(--paper)", background: notifOpen ? "rgba(255,244,226,.12)" : "rgba(255,244,226,.06)", border: "1px solid rgba(255,244,226,.1)", position: "relative" }}><Ico.Bell />{unread > 0 && <span style={{ position: "absolute", top: -4, insetInlineEnd: -4, minWidth: 18, height: 18, borderRadius: 99, background: accent, color: "#fff", border: "2px solid #0F0B08", display: "grid", placeItems: "center", fontSize: 9 }}>{lang === "fa" ? toFa(unread) : unread}</span>}</button>
            {notifOpen && <NotificationPanel notifs={notifs} onMarkAll={() => setNotifs(notifs.map(item => ({ ...item, unread: false })))} onClose={() => setNotifOpen(false)} />}
          </div>
          <div style={{ position: "relative" }}>
            <button onClick={() => { setProfileOpen(value => !value); setNotifOpen(false); }} style={{ height: 42, padding: "0 7px 0 12px", borderRadius: 99, display: "flex", alignItems: "center", gap: 8, color: "var(--paper)", background: profileOpen ? "rgba(255,244,226,.12)" : "rgba(255,244,226,.06)", border: "1px solid rgba(255,244,226,.1)" }}><span style={{ width: 28, height: 28, borderRadius: 99, background: "#5B6B3A", display: "grid", placeItems: "center", fontWeight: 800 }}>{lang === "fa" ? "گ" : "G"}</span><span className="hide-mobile" style={{ fontSize: 12, fontWeight: 700 }}>{lang === "fa" ? "گلپر صدری" : "Golpar S."}</span></button>
            {profileOpen && <div style={{ position: "absolute", top: "calc(100% + 9px)", insetInlineEnd: 0, width: 220, padding: 8, borderRadius: 14, background: "#17110D", border: "1px solid rgba(255,244,226,.13)", boxShadow: "0 24px 60px rgba(0,0,0,.5)" }}><button onClick={() => { navigate("settings"); setProfileOpen(false); }} style={{ width: "100%", padding: 11, borderRadius: 9, color: "var(--paper)", textAlign: "start" }}>{lang === "fa" ? "تنظیمات حساب" : "Account settings"}</button><button onClick={logout} style={{ width: "100%", padding: 11, borderRadius: 9, color: "#FF8C7C", textAlign: "start" }}>{lang === "fa" ? "خروج از حساب مدیر" : "Sign out"}</button></div>}
          </div>
        </div>
      </header>
      <div style={{ marginTop: 22 }}>
        {tab === "overview" && <FunctionalOverview accent={accent} onNavigate={navigate} />}
        {tab === "orders" && <FunctionalOrdersTab accent={accent} search={search} />}
        {tab === "menu" && <FunctionalMenuTab accent={accent} />}
        {tab === "customers" && <CustomersTab accent={accent} />}
        {tab === "staff" && <FunctionalStaffTab accent={accent} />}
        {tab === "reports" && <FunctionalReportsTab accent={accent} />}
        {tab === "settings" && <FunctionalSettingsTab accent={accent} />}
      </div>
    </main>
    {(notifOpen || profileOpen) && <div onClick={() => { setNotifOpen(false); setProfileOpen(false); }} style={{ position: "fixed", inset: 0, zIndex: 6 }} />}
    <style>{`
      .admin-main option{background:#17110D;color:#FFF4E2}
      @media (max-width:1024px){.admin-sidebar{padding:14px 12px!important;gap:12px!important}.admin-nav{flex-direction:row!important;overflow-x:auto;gap:5px!important}.admin-nav button{flex-shrink:0}.admin-main{padding:18px 15px!important}}
      @media (max-width:560px){.admin-sidebar>div:first-child{display:none}.admin-sidebar>div:nth-child(2){display:none}.admin-main{padding-top:14px!important}}
    `}</style>
  </div>;
}

window.Admin = AdminApp;
window.AdminLogin = AdminLogin;
