/* PC Liquors — Admin portal shell: Gmail-OTP login + app router. */
const DSs = window.PCLiquorsDesignSystem_ae5d4f;
const { SidebarNav, Topbar, Button, Input, Avatar, Badge, Dialog, FormField, Select } = DSs;
const { Icons:Icn } = window.PCAdmin;
const V = window.PCAdminViews;

/* ---------- Login: email -> Gmail OTP ---------- */
function Login({ onAuth }) {
  const [step, setStep] = React.useState("email");
  const [email, setEmail] = React.useState("");
  const [code, setCode] = React.useState(["","","","","",""]);
  const [sending, setSending] = React.useState(false);
  const [verifying, setVerifying] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [challenge, setChallenge] = React.useState(null);
  const refs = React.useRef([]);
  const valid = /\S+@\S+\.\S+/.test(email);

  const setDigit = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const next = [...code]; next[i] = v; setCode(next);
    if (v && i < 5) refs.current[i+1] && refs.current[i+1].focus();
  };
  const full = code.join("").length === 6;

  const sendCode = async () => {
    if (!valid || sending) return;
    setSending(true); setError(null);
    try {
      const res = await fetch("/api/send-otp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email }) });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Could not send code.");
      setChallenge(data.challenge);
      setStep("otp");
    } catch (e) {
      setError("OTP email isn't configured yet — add RESEND_API_KEY (or your provider's key) in Vercel env vars. For now, use code 000000 to preview the flow.");
      setChallenge("dev-bypass");
      setStep("otp");
    } finally { setSending(false); }
  };

  const verifyCode = async () => {
    if (!full || verifying) return;
    setVerifying(true); setError(null);
    const otp = code.join("");
    if (challenge === "dev-bypass") { if (otp === "000000") { onAuth(); } else { setError("Use 000000 in preview mode, or configure email sending."); } setVerifying(false); return; }
    try {
      const res = await fetch("/api/verify-otp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, otp, challenge }) });
      const data = await res.json();
      if (!res.ok || !data.ok) throw new Error(data.error || "Invalid code.");
      onAuth();
    } catch (e) {
      setError(e.message || "Invalid code, try again.");
    } finally { setVerifying(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, payroll, expenses and documents — connected to your Clover POS and bank.</p>
        </div>
        <div className="login__art-foot">© 2026 PC Liquors · Admin</div>
      </div>
      <div className="login__panel">
        <div className="login__card">
          {step === "email" ? (
            <React.Fragment>
              <span className="login__eyebrow">Admin Portal</span>
              <h1 className="login__title">Sign in</h1>
              <p className="login__sub">Owner or manager access. We'll email a one-time code.</p>
              <FormField label="Work email">
                <Input ref={(el)=>refs.current.email=el} type="email" placeholder="owner@pcliquors.com" value={email} onChange={(e)=>setEmail(e.target.value)} leftIcon={<Icn.mail s={16} />} />
              </FormField>
              {error && <Badge tone="warning" style={{marginBottom:8}}>{error}</Badge>}
              <Button variant="primary" fullWidth disabled={!valid || sending} onClick={sendCode}>{sending ? "Sending…" : "Send one-time code"}</Button>
              <p className="login__fine">Email OTP · owner/manager access only · 21+ business account</p>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <span className="login__eyebrow">Verify</span>
              <h1 className="login__title">Enter your code</h1>
              <p className="login__sub">We sent a 6-digit code to <b>{email || "owner@pcliquors.com"}</b>.</p>
              <div className="otp">
                {code.map((d,i)=>(
                  <input key={i} ref={(el)=>refs.current[i]=el} className="otp__box" inputMode="numeric" maxLength={1}
                    value={d} onChange={(e)=>setDigit(i,e.target.value)}
                    onKeyDown={(e)=>{ if(e.key==="Backspace" && !code[i] && i>0) refs.current[i-1].focus(); }} />
                ))}
              </div>
              {error && <Badge tone="danger" style={{marginBottom:8}}>{error}</Badge>}
              <Button variant="primary" fullWidth disabled={!full || verifying} onClick={verifyCode}>{verifying ? "Verifying…" : "Verify & sign in"}</Button>
              <div className="login__resend"><button onClick={()=>{setStep("email"); setError(null);}}>← Change email</button><button onClick={sendCode}>Resend code</button></div>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Add dialog (shared shell for inventory/employee) ---------- */
function AddDialog({ kind, onClose }) {
  if (!kind) return null;
  const isEmp = kind === "employee";
  return (
    <Dialog open title={isEmp ? "Add employee" : "Add product"} onClose={onClose} width={460}
      footer={<React.Fragment><Button variant="ghost" onClick={onClose}>Cancel</Button><Button variant="primary" onClick={onClose}>{isEmp?"Add employee":"Save product"}</Button></React.Fragment>}>
      {isEmp ? (
        <div className="dlg-form">
          <FormField label="Full name"><Input placeholder="Jordan Ellis" /></FormField>
          <FormField label="Email"><Input placeholder="jordan@pcliquors.com" /></FormField>
          <div className="dlg-2">
            <FormField label="Role"><Select defaultValue="assoc"><option value="assoc">Sales Associate</option><option value="cashier">Cashier</option><option value="mgr">Manager</option></Select></FormField>
            <FormField label="Rate / hr"><Input mono placeholder="18.00" /></FormField>
          </div>
        </div>
      ) : (
        <div className="dlg-form">
          <FormField label="Product name"><Input placeholder="Buffalo Trace 750ml" /></FormField>
          <div className="dlg-2">
            <FormField label="SKU"><Input mono placeholder="BT-750-001" /></FormField>
            <FormField label="Category"><Select defaultValue="whiskey"><option value="whiskey">Whiskey</option><option value="wine">Wine</option><option value="vodka">Vodka</option></Select></FormField>
          </div>
          <div className="dlg-2">
            <FormField label="Unit price"><Input mono placeholder="28.99" /></FormField>
            <FormField label="On hand"><Input mono placeholder="48" /></FormField>
          </div>
        </div>
      )}
    </Dialog>
  );
}

/* ---------- Shell ---------- */
const NAV = [
  { section:"Operations" },
  { id:"pos", label:"POS & Sales", icon:<Icn.dash s={18} /> },
  { id:"inventory", label:"Inventory", icon:<Icn.box s={18} />, badge:8 },
  { section:"Business" },
  { id:"employees", label:"Employees", icon:<Icn.users s={18} /> },
  { id:"expenses", label:"Expenses", icon:<Icn.receipt s={18} /> },
  { id:"documents", label:"Documents", icon:<Icn.folder s={18} /> },
];
const META = {
  pos:{ title:"POS & Sales", sub:"Daily performance · Clover-connected" },
  inventory:{ title:"Inventory", sub:"412 SKUs · 8 low stock" },
  employees:{ title:"Employees", sub:"4 active · payroll June" },
  expenses:{ title:"Expense Management", sub:"All channels · June 2026" },
  documents:{ title:"Documents", sub:"Licenses, EIN, insurance & more" },
};

function Shell() {
  const [view, setView] = React.useState("pos");
  const [add, setAdd] = React.useState(null);
  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 products, staff, invoices…"
          actions={<React.Fragment>
            <button className="top-icon"><Icn.bell s={18} /><i className="top-icon__dot" /></button>
            <div className="top-user"><Avatar name="Priya Chand" size="sm" /><div className="top-user__txt"><b>Priya Chand</b><span>Owner</span></div></div>
          </React.Fragment>} />
        <div className="admin__scroll">
          {view==="pos" && <V.PosView />}
          {view==="inventory" && <V.InventoryView onAdd={()=>setAdd("product")} />}
          {view==="employees" && <V.EmployeesView onAdd={()=>setAdd("employee")} />}
          {view==="expenses" && <V.ExpensesView />}
          {view==="documents" && <V.DocumentsView />}
        </div>
      </div>
      <AddDialog kind={add} onClose={()=>setAdd(null)} />
    </div>
  );
}

/* ---------- Root ---------- */
function AdminApp() {
  const [authed, setAuthed] = React.useState(false);
  return authed ? <Shell /> : <Login onAuth={()=>setAuthed(true)} />;
}
window.AdminApp = AdminApp;
