/* PC Liquors — Admin portal shell: admin-ID + password sign-in, module router. */
const DSs = window.PCLiquorsDesignSystem_ae5d4f;
const { SidebarNav, Topbar, Button, Input, Avatar, Badge, Alert, Dialog, FormField, Spinner } = DSs;
const { Icons:Icn, api } = window.PCAdmin;
const V = window.PCAdminViews;

/* ---------- Sign in: admin ID + password ---------- */
function Login({ onAuth }) {
  const [uid, setUid] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);

  const ready = uid.trim() && password;

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!ready || busy) return;
    setBusy(true); setError(null);
    try {
      const res = await api.login(uid.trim().toLowerCase(), password);
      api.setToken(res.token);
      onAuth(res.user);
    } catch (err) {
      setError(err.message);
      setPassword("");
    } finally { setBusy(false); }
  };

  return (
    <div className="login">
      <div className="login__art">
        <img className="login__logo" src="../assets/logo-horizontal-light.svg" alt="PC Liquors" />
        <div className="login__art-copy">
          <h2>Run the whole shop<br/>from one portal.</h2>
          <p>Sales, inventory, offers, staff, utilities, expenses and documents — in one place.</p>
        </div>
        <div className="login__art-foot">© 2026 PC Liquors · Admin</div>
      </div>
      <div className="login__panel">
        <form className="login__card" onSubmit={submit}>
          <span className="login__eyebrow">Admin Portal</span>
          <h1 className="login__title">Sign in</h1>
          <p className="login__sub">Owner and manager access only.</p>

          <FormField label="Admin ID" htmlFor="uid">
            <Input id="uid" name="username" autoComplete="username" mono placeholder="pcl-owner"
              value={uid} onChange={(e)=>setUid(e.target.value)} leftIcon={<Icn.user s={16} />} />
          </FormField>
          <FormField label="Password" htmlFor="pw">
            <div className="pw-wrap">
              <Input id="pw" name="password" autoComplete="current-password"
                type={show ? "text" : "password"} placeholder="••••••••••"
                value={password} onChange={(e)=>setPassword(e.target.value)} leftIcon={<Icn.lock s={16} />} />
              <button type="button" className="pw-toggle" onClick={()=>setShow((s)=>!s)}
                aria-label={show ? "Hide password" : "Show password"}><Icn.eye s={16} /></button>
            </div>
          </FormField>

          {error && <Alert tone="danger" style={{marginBottom:"0.75rem"}}><span>{error}</span></Alert>}

          <Button type="submit" variant="primary" fullWidth disabled={!ready || busy}>
            {busy ? "Signing in…" : "Sign in"}
          </Button>
          <p className="login__fine">Locked for 15 minutes after 5 failed attempts · 21+ business account</p>
        </form>
      </div>
    </div>
  );
}

/* ---------- First sign-in: force a new password ---------- */
function ForcePasswordChange({ user, onSkip }) {
  return (
    <div className="force-pw">
      <div className="force-pw__card">
        <span className="force-pw__ic"><Icn.shield s={24} /></span>
        <h1>Choose your own password</h1>
        <p>You're signed in as <b>{user.name}</b> with the password that was issued to you.
           Set a private one before you carry on — it takes a moment.</p>
        <V.ChangePassword forced />
        <button className="force-pw__skip" onClick={onSkip}>Skip for now</button>
      </div>
    </div>
  );
}

/* ---------- Shell ---------- */
const NAV = [
  { section:"Operations" },
  { id:"pos", label:"POS & Sales", icon:<Icn.dash s={18} /> },
  { id:"inventory", label:"Inventory", icon:<Icn.box s={18} /> },
  { id:"ads", label:"Ads & Offers", icon:<Icn.megaphone s={18} /> },
  { section:"Business" },
  { id:"employees", label:"Employees", icon:<Icn.users s={18} /> },
  { id:"expenses", label:"Expenses", icon:<Icn.receipt s={18} /> },
  { id:"utilities", label:"Utilities", icon:<Icn.bolt s={18} /> },
  { id:"documents", label:"Documents", icon:<Icn.folder s={18} /> },
  { section:"Account" },
  { id:"settings", label:"Settings", icon:<Icn.settings s={18} /> },
];

const META = {
  pos:        { title:"POS & Sales",      sub:"Store performance at a glance" },
  inventory:  { title:"Inventory",        sub:"Catalogue, stock levels & margin" },
  ads:        { title:"Ads & Offers",     sub:"Promotions that label the storefront" },
  employees:  { title:"Employees",        sub:"Team, hours & gross payroll" },
  expenses:   { title:"Expense Management", sub:"Money in and out, all channels" },
  utilities:  { title:"Utilities",        sub:"Recurring bills & business services" },
  documents:  { title:"Documents",        sub:"Licences, EIN, insurance & contracts" },
  settings:   { title:"Settings",         sub:"Your password, admin logins & activity" },
};

const SEARCH_HINT = "Search products, staff, offers, invoices…";

function Shell({ user, onSignOut }) {
  const [view, setView] = React.useState("pos");
  const [navOpen, setNavOpen] = React.useState(false);
  const m = META[view];

  return (
    <div className="admin">
      <SidebarNav items={NAV} value={view} className={navOpen ? "is-open" : ""}
        onChange={(id)=>{ setView(id); setNavOpen(false); }} />
      <div className={"admin__scrim" + (navOpen ? " is-open" : "")} onClick={()=>setNavOpen(false)} />
      <div className="admin__main">
        <button className="admin__menu-btn" aria-label="Menu" aria-expanded={navOpen} onClick={()=>setNavOpen((o)=>!o)}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            {navOpen ? <path d="M18 6L6 18M6 6l12 12"/> : <path d="M3 12h18M3 6h18M3 18h18"/>}
          </svg>
        </button>
        <Topbar title={m.title} subtitle={m.sub} search searchPlaceholder={SEARCH_HINT}
          actions={<React.Fragment>
            <a className="top-icon" href="../" title="View the storefront" target="_blank" rel="noreferrer"><Icn.eye s={18} /></a>
            <div className="top-user" onClick={()=>setView("settings")} role="button" tabIndex={0}>
              <Avatar name={user.name} size="sm" />
              <div className="top-user__txt"><b>{user.name}</b><span>{user.role}</span></div>
            </div>
            <button className="top-icon top-icon--out" onClick={onSignOut} title="Sign out"><Icn.logout s={18} /></button>
          </React.Fragment>} />
        <div className="admin__scroll">
          {view==="pos"        && <V.PosView go={setView} />}
          {view==="inventory"  && <V.InventoryView />}
          {view==="ads"        && <V.AdsView />}
          {view==="employees"  && <V.EmployeesView />}
          {view==="expenses"   && <V.ExpensesView />}
          {view==="utilities"  && <V.UtilitiesView />}
          {view==="documents"  && <V.DocumentsView />}
          {view==="settings"   && <V.SettingsView user={user} />}
        </div>
      </div>
    </div>
  );
}

/* ---------- Root ---------- */
function AdminApp() {
  const [user, setUser] = React.useState(null);
  const [booting, setBooting] = React.useState(true);
  const [skippedPw, setSkippedPw] = React.useState(false);

  const signOut = React.useCallback(() => { api.setToken(null); setUser(null); }, []);

  // A stored token survives a refresh — check it's still good before showing the portal.
  React.useEffect(() => {
    api.onExpire = () => setUser(null);
    if (!api.token()) { setBooting(false); return; }
    api.me()
      .then((d)=> setUser(d.user))
      .catch(()=> api.setToken(null))
      .finally(()=> setBooting(false));
  }, []);

  if (booting) {
    return <div className="admin-boot"><Spinner size="lg" /><span>Signing you in…</span></div>;
  }
  if (!user) return <Login onAuth={setUser} />;
  if (user.mustChangePassword && !skippedPw) {
    return <ForcePasswordChange user={user} onSkip={()=>setSkippedPw(true)} />;
  }
  return <Shell user={user} onSignOut={signOut} />;
}

window.AdminApp = AdminApp;
