/* Quote Connect — Admin portal (store-backed, fully persistent)
   Admin can change anything: supplier logins, business details, verification,
   per-supplier fee, coverage area (incl. Australia wide), categories & sub
   categories. Deletes are SOFT by default (archive → restorable); permanent
   removal is an explicit admin-only action. */

/* NOTE (2026-08-14): the hard-coded offline admin credentials that used to live
   here were removed. This file is served publicly, so the password was readable
   by anyone who viewed source. It only worked while Supabase was unconfigured,
   but that is exactly the state the site falls back into if the keys in
   parts/supabase-config.js are ever blank or wrong — which would have turned it
   into a live backdoor. Admin login now always goes through Supabase Auth. */

function AdminLogin({ onLogin, store }) {
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setBusy(true);
    if (!store.isOnline()) {
      setBusy(false);
      setErr("Not connected to Supabase — admin login is unavailable. Check parts/supabase-config.js.");
      return;
    }
    const res = await store.signInAdmin(email, pw);
    setBusy(false);
    if (res.error) setErr(res.error);
    else onLogin();
  };
  return (
    <div className="qc-wrap-narrow">
      <div className="ad-login card">
        <div className="ad-login-mark"><Icon name="shield-half" size={22} /></div>
        <h1 className="display ad-login-h">Admin portal</h1>
        <p className="ad-login-sub">Internal access only. Manage suppliers, logins, categories and enquiry routing.</p>
        <form className="sp-login-form" onSubmit={submit}>
          <label className="qf-field"><span className="qf-label">Admin email</span>
            <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); setErr(false); }} /></label>
          <label className="qf-field"><span className="qf-label">Password</span>
            <input type="password" value={pw} onChange={(e) => { setPw(e.target.value); setErr(false); }} /></label>
          {err && <div className="ad-login-err mono"><Icon name="alert-circle" size={13} /> {err}</div>}
          <Btn variant="dark" size="lg" full type="submit" disabled={busy}>{busy ? "Signing in…" : <>Log in <Icon name="arrow-right" size={17} /></>}</Btn>
        </form>
      </div>
    </div>
  );
}

function SupplierEditor({ sup, store, onClose }) {
  const cats = store.categories();
  const [pw, setPw] = React.useState("");
  const [saved, setSaved] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const set = (patch) => store.updateSupplier(sup.id, patch);
  const gen = () => {
    const s = "abcdefghjkmnpqrstuvwxyz23456789";
    let out = ""; for (let i = 0; i < 12; i++) out += s[Math.floor(Math.random() * s.length)];
    setPw(out); setCopied(false);
  };
  const applyPw = () => { set({ pw }); setPw(""); setSaved(true); setTimeout(() => setSaved(false), 1800); };
  const toggleCat = (id) => set({ cats: (sup.cats || []).includes(id) ? sup.cats.filter((x) => x !== id) : [...(sup.cats || []), id] });
  const toggleState = (st) => set({ states: (sup.states || []).includes(st) ? sup.states.filter((x) => x !== st) : [...(sup.states || []), st] });

  return (
    <div className="ad-editor card">
      <div className="ad-editor-head">
        <SupAvatar sup={sup} size={44} />
        <div className="ad-editor-id">
          <div className="ad-editor-name">{sup.name}</div>
          <div className="mono ad-editor-loc">{sup.loc || "—"}{sup.archived ? " · ARCHIVED" : ""}</div>
        </div>
        <button className="ad-close" onClick={onClose} aria-label="Close"><Icon name="x" size={18} /></button>
      </div>

      {sup.archived && (
        <div className="ad-archived-note">
          <Icon name="archive" size={15} />
          <span>This supplier is archived — hidden from the site but all data is kept.</span>
        </div>
      )}

      <div className="ad-sec">
        <div className="ad-sec-t"><Icon name="key-round" size={15} /> Login credentials</div>
        <div className="ad-cred">
          <span className="ad-cred-k mono">Username</span>
          <input className="mono" value={sup.user || ""} onChange={(e) => set({ user: e.target.value })} />
        </div>
        <div className="ad-cred">
          <span className="ad-cred-k mono">Login email</span>
          <input className="mono" type="email" value={sup.email || ""} onChange={(e) => set({ email: e.target.value })} />
        </div>
        <div className="ad-cred">
          <span className="ad-cred-k mono">New password</span>
          <input className="mono" type="text" value={pw} onChange={(e) => setPw(e.target.value)} />
          <button className="ad-mini" onClick={gen}><Icon name="refresh-cw" size={13} /> Generate</button>
        </div>
        <div className="ad-cred-actions">
          {store.isOnline() ? (
            <>
              <Btn variant="primary" size="sm" disabled={!pw || pw.length < 8} onClick={async () => {
                const r = await store.adminSetPassword(sup.userId, pw);
                if (r.error) window.alert(r.error);
                else { setPw(""); setSaved(true); setTimeout(() => setSaved(false), 1800); }
              }}>{saved ? <><Icon name="check" size={14} /> Password set</> : "Set password"}</Btn>
              <Btn variant="outline" size="sm" onClick={async () => {
                const r = await store.sendPasswordReset(sup.email);
                window.alert(r.error ? r.error : "Password reset email sent to " + sup.email);
              }}><Icon name="mail" size={14} /> Send reset email</Btn>
            </>
          ) : (
            <Btn variant="primary" size="sm" disabled={!pw} onClick={applyPw}>{saved ? <><Icon name="check" size={14} /> Saved</> : "Set password"}</Btn>
          )}
          <Btn variant="outline" size="sm" disabled={!pw} onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1600); }}>
            <Icon name={copied ? "check" : "copy"} size={14} /> {copied ? "Copied" : "Copy"}
          </Btn>
          <Btn variant="ghost" size="sm"><Icon name="mail" size={14} /> Email to supplier</Btn>
        </div>
        <div className="ad-cred-current mono">Current password: <b>{sup.pw ? "•".repeat(Math.min(sup.pw.length, 12)) : "not set"}</b></div>
      </div>

      <div className="ad-sec">
        <div className="ad-sec-t"><Icon name="building-2" size={15} /> Business details</div>
        <div className="ad-grid2">
          <label className="qf-field"><span className="qf-label">Business name</span>
            <input value={sup.name} onChange={(e) => set({ name: e.target.value })} /></label>
          <label className="qf-field"><span className="qf-label">ABN</span>
            <input className="mono" value={sup.abn || ""} onChange={(e) => set({ abn: e.target.value })} /></label>
          <label className="qf-field"><span className="qf-label">Location</span>
            <input value={sup.loc || ""} onChange={(e) => set({ loc: e.target.value })} /></label>
          <label className="qf-field"><span className="qf-label">Phone</span>
            <input value={sup.phone || ""} onChange={(e) => set({ phone: e.target.value })} /></label>
        </div>
      </div>

      <div className="ad-sec">
        <div className="ad-sec-t"><Icon name="badge-check" size={15} /> Verification &amp; subscription</div>
        <div className="ad-grid2">
          <label className="qf-field"><span className="qf-label">Account status</span>
            <div className="qf-select-wrap"><select value={sup.status} onChange={(e) => set({ status: e.target.value, verified: e.target.value === "verified" })}>
              <option value="verified">Verified</option><option value="pending">Pending verification</option><option value="suspended">Suspended</option>
            </select><Icon name="chevron-down" size={16} /></div></label>
          <label className="qf-field"><span className="qf-label">Subscription</span>
            <div className="qf-select-wrap"><select value={sup.sub} onChange={(e) => set({ sub: e.target.value })}>
              <option value="active">Active</option><option value="past_due">Past due</option><option value="inactive">Inactive</option>
            </select><Icon name="chevron-down" size={16} /></div></label>
          <label className="qf-field"><span className="qf-label">Plan</span>
            <div className="qf-select-wrap"><select value={sup.plan} onChange={(e) => set({ plan: e.target.value })}>
              <option>Starter</option><option>Growth</option><option>Enterprise</option>
            </select><Icon name="chevron-down" size={16} /></div></label>
        </div>
      </div>

      <div className="ad-sec">
        <div className="ad-sec-t"><Icon name="dollar-sign" size={15} /> Subscription fee <span className="ad-sec-note mono">per supplier</span></div>
        <div className="ad-fee">
          <div className="ad-fee-in">
            <span className="mono">$</span>
            <input className="mono" inputMode="numeric" value={sup.fee ?? 0}
              onChange={(e) => set({ fee: e.target.value.replace(/[^0-9]/g, "") })} />
          </div>
          <div className="qf-select-wrap ad-fee-cycle">
            <select value={sup.cycle || "monthly"} onChange={(e) => set({ cycle: e.target.value })}>
              <option value="monthly">per month</option>
              <option value="quarterly">per quarter</option>
              <option value="annual">per year</option>
            </select><Icon name="chevron-down" size={16} />
          </div>
        </div>
        <div className="ad-fee-presets">
          {[79, 149, 199, 249, 0].map((v) => (
            <button key={v} className={"ad-mini" + (Number(sup.fee) === v ? " on" : "")} onClick={() => set({ fee: v })}>
              {v === 0 ? "Free" : "$" + v}
            </button>
          ))}
        </div>
      </div>

      <div className="ad-sec">
        <div className="ad-sec-t"><Icon name="map" size={15} /> Coverage area <span className="ad-sec-note mono">admin-only</span></div>
        <button className={"ad-auwide" + (sup.auWide ? " on" : "")} onClick={() => set({ auWide: !sup.auWide })}>
          <span className="ad-auwide-ic"><Icon name={sup.auWide ? "check" : "globe"} size={16} /></span>
          <span className="ad-auwide-t"><b>Australia wide</b><i>Receives every matching enquiry, any location</i></span>
          <span className={"ad-switch" + (sup.auWide ? " on" : "")} />
        </button>
        {!sup.auWide && (
          <div className="ad-area">
            <div className="ad-area-l mono">States / territories served</div>
            <div className="sp-acc-cats">
              {window.QC_DATA.STATES.map((st) => {
                const on = (sup.states || []).includes(st);
                return (
                  <button key={st} className={"sp-cat-chip" + (on ? " on" : "")} onClick={() => toggleState(st)}>
                    <Icon name={on ? "check" : "plus"} size={13} /> {st}
                  </button>
                );
              })}
            </div>
            <div className="ad-area-l mono" style={{ marginTop: 16 }}>Radius from base</div>
            <div className="ad-radius">
              <input type="range" className="cov-slider" min="80" max="800" step="10" value={sup.radiusKm || 250}
                onChange={(e) => set({ radiusKm: Number(e.target.value) })} />
              <span className="ad-radius-v mono">{sup.radiusKm || 250} km</span>
            </div>
          </div>
        )}
      </div>

      <div className="ad-sec">
        <div className="ad-sec-t"><Icon name="layers" size={15} /> Categories served <span className="ad-sec-note mono">drives which enquiries are emailed</span></div>
        <div className="sp-acc-cats">
          {cats.map((c) => (
            <button key={c.id} className={"sp-cat-chip" + ((sup.cats || []).includes(c.id) ? " on" : "")} onClick={() => toggleCat(c.id)}>
              <Icon name={(sup.cats || []).includes(c.id) ? "check" : "plus"} size={13} /> {c.name}
            </button>
          ))}
        </div>
      </div>

      <div className="ad-editor-foot">
        <span className="ad-autosave mono"><Icon name="check" size={13} /> All changes saved automatically</span>
        {sup.archived ? (
          <>
            <Btn variant="primary" size="sm" onClick={() => store.restoreSupplier(sup.id)}><Icon name="rotate-ccw" size={14} /> Restore</Btn>
            <button className="ad-danger" onClick={() => {
              if (window.confirm("Permanently delete " + sup.name + "? This cannot be undone.")) { store.destroySupplier(sup.id); onClose(); }
            }}>Delete permanently</button>
          </>
        ) : (
          <button className="ad-danger" onClick={() => {
            if (window.confirm("Archive " + sup.name + "? Their data is kept and can be restored.")) { store.archiveSupplier(sup.id); onClose(); }
          }}>Archive supplier</button>
        )}
      </div>
    </div>
  );
}

function CategoryManager({ store, t }) {
  const [showArchived, setShowArchived] = React.useState(false);
  const list = store.categories(showArchived);
  const [openCat, setOpenCat] = React.useState(list[0] ? list[0].id : null);
  const [newCat, setNewCat] = React.useState("");
  const [newSub, setNewSub] = React.useState("");
  const [editing, setEditing] = React.useState(null);
  const [draft, setDraft] = React.useState("");
  const [imgFor, setImgFor] = React.useState(null);
  const [imgDraft, setImgDraft] = React.useState("");
  const [subImgFor, setSubImgFor] = React.useState(null);   // index within sel.subs
  const [subImgDraft, setSubImgDraft] = React.useState("");
  const sel = store.category(openCat) || list[0] || null;

  const openImg = (c) => { setImgFor(c.id); setImgDraft(c.img || ""); };
  const saveImg = () => { if (imgFor) store.updateCategory(imgFor, { img: imgDraft.trim() }); setImgFor(null); setImgDraft(""); };
  const [upBusy, setUpBusy] = React.useState(false);
  const uploadImg = async (file) => {
    if (!file) return;
    setUpBusy(true);
    const r = await store.uploadImage(file, "categories");
    setUpBusy(false);
    if (r.error) window.alert(r.error); else setImgDraft(r.url);
  };
  const openSubImg = (i) => { setSubImgFor(i); setSubImgDraft(QC_SUBIMG(sel.subs[i])); };
  const saveSubImg = () => {
    if (subImgFor == null || !sel) return;
    store.setSubs(sel.id, sel.subs.map((x, k) => (k === subImgFor ? { name: QC_SUBNAME(x), img: subImgDraft.trim() } : x)));
    setSubImgFor(null); setSubImgDraft("");
  };
  const uploadSubImg = async (file) => {
    if (!file) return;
    setUpBusy(true);
    const r = await store.uploadImage(file, "subcategories");
    setUpBusy(false);
    if (r.error) window.alert(r.error); else setSubImgDraft(r.url);
  };

  const addCat = () => {
    const name = newCat.trim(); if (!name) return;
    const c = store.addCategory(name);
    if (c) { setNewCat(""); setOpenCat(c.id); openImg(c); }
  };
  const addSub = () => {
    const v = newSub.trim(); if (!v || !sel || sel.subs.includes(v)) { setNewSub(""); return; }
    store.setSubs(sel.id, [...sel.subs, v]); setNewSub("");
  };
  const saveEdit = () => {
    const v = draft.trim();
    if (!v || !editing) { setEditing(null); return; }
    if (editing.startsWith("cat:")) store.updateCategory(editing.slice(4), { name: v });
    else { const i = Number(editing.split(":")[2]); store.setSubs(sel.id, sel.subs.map((x, k) => (k === i ? { name: v, img: QC_SUBIMG(x) } : x))); }
    setEditing(null);
  };
  const move = (i, dir) => {
    const j = i + dir; if (j < 0 || j >= sel.subs.length) return;
    const arr = [...sel.subs]; [arr[i], arr[j]] = [arr[j], arr[i]];
    store.setSubs(sel.id, arr);
  };

  return (
    <div className="ad-cats">
      <div className="ad-panel card">
        <div className="ad-panel-top">
          <div>
            <h3 className="ad-panel-h">Categories</h3>
            <p className="ad-panel-p">Create, rename or archive the categories buyers can request quotes for.</p>
          </div>
          <label className="ad-showarch mono"><input type="checkbox" checked={showArchived} onChange={(e) => setShowArchived(e.target.checked)} /> Show archived</label>
        </div>
        <div className="ad-catlist">
          {list.map((c) => (
            <div key={c.id} className={"ad-catrow" + (c.id === (sel && sel.id) ? " on" : "") + (c.archived ? " arch" : "")} onClick={() => setOpenCat(c.id)}>
              <CatVisual cat={{ ...c, img: c.img || "" }} iconStyle={c.img ? t.icons : "mono"} size={32} radius={7} />
              {editing === "cat:" + c.id ? (
                <input className="ad-inline" autoFocus value={draft} onChange={(e) => setDraft(e.target.value)}
                  onBlur={saveEdit} onKeyDown={(e) => { if (e.key === "Enter") saveEdit(); if (e.key === "Escape") setEditing(null); }}
                  onClick={(e) => e.stopPropagation()} />
              ) : (
                <span className="ad-catrow-n">{c.name}{c.archived && <i className="ad-archtag mono">archived</i>}</span>
              )}
              <span className="mono ad-catrow-code">{c.code}</span>
              <span className="mono ad-catrow-count">{c.subs.length} subs</span>
              <button className="ad-icobtn" title="Change photo" onClick={(e) => { e.stopPropagation(); openImg(c); }}><Icon name="image" size={13} /></button>
              <button className="ad-icobtn" title="Rename" onClick={(e) => { e.stopPropagation(); setEditing("cat:" + c.id); setDraft(c.name); }}><Icon name="pencil" size={13} /></button>
              {c.archived ? (
                <>
                  <button className="ad-icobtn" title="Restore" onClick={(e) => { e.stopPropagation(); store.restoreCategory(c.id); }}><Icon name="rotate-ccw" size={13} /></button>
                  <button className="ad-icobtn danger" title="Delete permanently" onClick={(e) => { e.stopPropagation(); if (window.confirm("Permanently delete “" + c.name + "”? This cannot be undone.")) store.destroyCategory(c.id); }}><Icon name="trash-2" size={13} /></button>
                </>
              ) : (
                <button className="ad-icobtn danger" title="Archive" onClick={(e) => { e.stopPropagation(); store.archiveCategory(c.id); }}><Icon name="archive" size={13} /></button>
              )}
            </div>
          ))}
        </div>
        {imgFor && (
          <div className="ad-imgedit">
            <div className="ad-imgedit-head">
              <span className="ad-sec-t" style={{ margin: 0 }}><Icon name="image" size={15} /> Category photo</span>
              <button className="ad-icobtn" onClick={() => setImgFor(null)}><Icon name="x" size={13} /></button>
            </div>
            <div className="ad-imgedit-body">
              <div className="ad-imgprev">
                {imgDraft ? <img src={imgDraft} alt="" /> : <span className="mono">No photo</span>}
              </div>
              <div className="ad-imgfields">
                <label className="qf-field"><span className="qf-label">Image URL</span>
                  <input value={imgDraft} onChange={(e) => setImgDraft(e.target.value)} placeholder="https://…" /></label>
                <div className="ad-imgactions">
                  <label className="ad-mini ad-upload">
                    <Icon name="upload" size={13} /> {upBusy ? "Uploading…" : "Upload photo"}
                    <input type="file" accept="image/*" onChange={(e) => uploadImg(e.target.files[0])} />
                  </label>
                  {imgDraft && <button className="ad-mini" onClick={() => setImgDraft("")}><Icon name="trash-2" size={13} /> Clear</button>}
                </div>
                <div className="ad-imghint mono">Paste a link or upload from your device. Saved with the category.</div>
              </div>
            </div>
            <div className="ad-imgedit-foot">
              <Btn variant="primary" size="sm" onClick={saveImg}>Save photo</Btn>
              <Btn variant="ghost" size="sm" onClick={() => setImgFor(null)}>Cancel</Btn>
            </div>
          </div>
        )}
        <div className="ad-addrow">
          <input value={newCat} onChange={(e) => setNewCat(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") addCat(); }} placeholder="New category name" />
          <Btn variant="primary" size="sm" onClick={addCat}><Icon name="plus" size={15} /> Add category</Btn>
        </div>
      </div>

      <div className="ad-panel card">
        <h3 className="ad-panel-h">Sub categories{sel ? " — " + sel.name : ""}</h3>
        <p className="ad-panel-p">Brands and types buyers pick from inside {sel ? sel.name : "this category"}. Saved automatically.</p>
        {sel && (
          <>
            <div className="ad-subtools">
              <button className="ad-mini" onClick={() => store.setSubs(sel.id, [...sel.subs].sort((a, b) => a.localeCompare(b)))}>
                <Icon name="arrow-down-a-z" size={13} /> Sort A–Z
              </button>
              <button className="ad-mini" onClick={() => store.setSubs(sel.id, [...sel.subs].sort((a, b) => b.localeCompare(a)))}>
                <Icon name="arrow-up-a-z" size={13} /> Z–A
              </button>
            </div>
            <div className="ad-sublist">
              {sel.subs.map((sb, i) => (
                <div key={QC_SUBNAME(sb) + i} className="ad-subrow">
                  <span className="mono ad-subrow-i">{String(i + 1).padStart(2, "0")}</span>
                  <span className="ad-subthumb">
                    {QC_SUBIMG(sb) ? <img src={QC_SUBIMG(sb)} alt="" loading="lazy" /> : <Icon name="image" size={12} />}
                  </span>
                  {editing === "sub:" + sel.id + ":" + i ? (
                    <input className="ad-inline" autoFocus value={draft} onChange={(e) => setDraft(e.target.value)}
                      onBlur={saveEdit} onKeyDown={(e) => { if (e.key === "Enter") saveEdit(); if (e.key === "Escape") setEditing(null); }} />
                  ) : (
                    <span className="ad-subrow-n">{QC_SUBNAME(sb)}</span>
                  )}
                  <button className="ad-icobtn" title="Change photo" onClick={() => openSubImg(i)}><Icon name="image" size={13} /></button>
                  <button className="ad-icobtn" title="Move up" onClick={() => move(i, -1)}><Icon name="chevron-up" size={13} /></button>
                  <button className="ad-icobtn" title="Move down" onClick={() => move(i, 1)}><Icon name="chevron-down" size={13} /></button>
                  <button className="ad-icobtn" title="Rename" onClick={() => { setEditing("sub:" + sel.id + ":" + i); setDraft(sb); }}><Icon name="pencil" size={13} /></button>
                  <button className="ad-icobtn danger" title="Remove" onClick={() => { if (window.confirm("Remove “" + QC_SUBNAME(sb) + "” from " + sel.name + "?")) store.setSubs(sel.id, sel.subs.filter((_, x) => x !== i)); }}><Icon name="trash-2" size={13} /></button>
                </div>
              ))}
              {sel.subs.length === 0 && <div className="ad-subempty mono">No sub categories yet.</div>}
            </div>
            {subImgFor != null && sel.subs[subImgFor] && (
              <div className="ad-imgedit">
                <div className="ad-imgedit-head">
                  <span className="ad-sec-t" style={{ margin: 0 }}><Icon name="image" size={15} /> Photo — {QC_SUBNAME(sel.subs[subImgFor])}</span>
                  <button className="ad-icobtn" onClick={() => setSubImgFor(null)}><Icon name="x" size={13} /></button>
                </div>
                <div className="ad-imgedit-body">
                  <div className="ad-imgprev">
                    {subImgDraft ? <img src={subImgDraft} alt="" /> : <span className="mono">No photo</span>}
                  </div>
                  <div className="ad-imgfields">
                    <label className="qf-field"><span className="qf-label">Image URL</span>
                      <input value={subImgDraft} onChange={(e) => setSubImgDraft(e.target.value)} placeholder="https://…" /></label>
                    <div className="ad-imgactions">
                      <label className="ad-mini ad-upload">
                        <Icon name="upload" size={13} /> {upBusy ? "Uploading…" : "Upload photo"}
                        <input type="file" accept="image/*" onChange={(e) => uploadSubImg(e.target.files[0])} />
                      </label>
                      {subImgDraft && <button className="ad-mini" onClick={() => setSubImgDraft("")}><Icon name="trash-2" size={13} /> Clear</button>}
                    </div>
                    <div className="ad-imghint mono">Shown on the sub category chip in the enquiry form.</div>
                  </div>
                </div>
                <div className="ad-imgedit-foot">
                  <Btn variant="primary" size="sm" onClick={saveSubImg}>Save photo</Btn>
                  <Btn variant="ghost" size="sm" onClick={() => setSubImgFor(null)}>Cancel</Btn>
                </div>
              </div>
            )}
            <div className="ad-addrow">
              <input value={newSub} onChange={(e) => setNewSub(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") addSub(); }} placeholder="New sub category" />
              <Btn variant="primary" size="sm" onClick={addSub}><Icon name="plus" size={15} /> Add sub</Btn>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function AdminScreen({ nav, t }) {
  const store = useStore();
  const [tab, setTab] = React.useState("suppliers");
  const [q, setQ] = React.useState("");
  const [selId, setSelId] = React.useState(null);
  const [showArchived, setShowArchived] = React.useState(false);

  // Trust the real Supabase session, never a browser flag. Showing the control
  // panel without a signed-in admin means every save fails the is_admin()
  // row-level security check and surfaces a confusing "row-level security
  // policy" database error instead of simply asking you to log in again.
  const authStatus = typeof store.status === "function" ? store.status() : {};
  const authed = !!authStatus.session && authStatus.role === "admin";

  const login = () => { setSelId(null); };
  const logout = () => { store.signOut(); setSelId(null); };

  if (store.isOnline() && !authStatus.authChecked) {
    return (
      <div className="screen admin-screen">
        <div className="qc-wrap-narrow"><p>Checking your session…</p></div>
      </div>
    );
  }

  if (!authed) return <div className="screen admin-screen"><AdminLogin onLogin={login} store={store} /></div>;

  const all = store.suppliers(showArchived);
  const ql = q.trim().toLowerCase();
  const list = all.filter((s) => !ql || s.name.toLowerCase().includes(ql) || (s.loc || "").toLowerCase().includes(ql) || (s.user || "").includes(ql) || (s.email || "").includes(ql));
  const sel = selId ? store.supplier(selId) : null;
  const pending = store.suppliers().filter((s) => s.status === "pending");
  const archivedCount = store.suppliers(true).filter((s) => s.archived).length;

  return (
    <div className="screen admin-screen">
      <div className="qc-wrap">
        <header className="ad-bar">
          <div className="ad-bar-id">
            <span className="ad-badge mono"><Icon name="shield-half" size={14} /> Admin</span>
            <span className="ad-bar-sub mono">Quote Connect control panel</span>
          </div>
          <Btn variant="outline" size="sm" onClick={logout}><Icon name="log-out" size={15} /> Log out</Btn>
        </header>

        <div className="ad-tabs">
          {[["suppliers", "Suppliers & logins", "users"], ["routing", "Enquiry routing", "route"], ["cats", "Categories", "layers"]].map(([k, l, ic]) => (
            <button key={k} className={"ad-tab" + (tab === k ? " on" : "")} onClick={() => setTab(k)}>
              <Icon name={ic} size={15} /> {l}
              {k === "suppliers" && pending.length > 0 && <span className="sp-filter-badge mono">{pending.length}</span>}
            </button>
          ))}
        </div>

        {tab === "suppliers" && (
          <div className={"ad-layout" + (sel ? " split" : "")}>
            <div className="ad-main">
              {pending.length > 0 && (
                <div className="ad-pending card">
                  <Icon name="user-plus" size={16} />
                  <span><b>{pending.length} application{pending.length > 1 ? "s" : ""} awaiting verification</b> — set their fee and coverage, then mark as Verified.</span>
                  <Btn variant="outline" size="sm" onClick={() => setSelId(pending[0].id)}>Review</Btn>
                </div>
              )}
              <div className="ad-search">
                <Icon name="search" size={16} />
                <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search suppliers, usernames, emails, locations" />
                <Btn variant="primary" size="sm" onClick={async () => {
                  const name = window.prompt("Business name for the new supplier:");
                  if (!name) return;
                  const s = await store.addSupplier({ name: name.trim() });
                  if (s) setSelId(s.id);
                }}><Icon name="plus" size={15} /> Add</Btn>
                <label className="ad-showarch mono"><input type="checkbox" checked={showArchived} onChange={(e) => setShowArchived(e.target.checked)} /> Archived ({archivedCount})</label>
              </div>
              <div className="ad-table card">
                <div className="ad-tr ad-th mono">
                  <span>Supplier</span><span>Coverage</span><span>Status</span><span>Fee</span><span></span>
                </div>
                {list.map((s) => (
                  <button key={s.id} className={"ad-tr" + (s.id === selId ? " on" : "") + (s.archived ? " arch" : "")} onClick={() => setSelId(s.id)}>
                    <span className="ad-td-name"><SupAvatar sup={s} size={30} /><span><b>{s.name}</b><i className="mono">{s.email}</i></span></span>
                    <span className="mono ad-td-user">{s.auWide ? "Australia wide" : (s.states || []).join(", ") || "—"}</span>
                    <span><span className={"ad-pill st-" + s.status}>{s.archived ? "archived" : s.status}</span></span>
                    <span className="mono ad-td-plan">{Number(s.fee) ? "$" + s.fee : "Free"}<i className={"ad-sub sub-" + s.sub} /></span>
                    <span className="ad-td-edit"><Icon name="pencil" size={14} /></span>
                  </button>
                ))}
                {list.length === 0 && <div className="ad-subempty mono" style={{ padding: 24 }}>No suppliers match.</div>}
              </div>
            </div>
            {sel && <SupplierEditor sup={sel} store={store} onClose={() => setSelId(null)} />}
          </div>
        )}

        {tab === "routing" && (
          <div className="ad-panel card">
            <h3 className="ad-panel-h">Enquiry → supplier email routing</h3>
            <p className="ad-panel-p">When a buyer submits an enquiry, it’s automatically emailed to every verified supplier whose categories match and whose coverage covers the buyer’s location (or who is set to Australia wide).</p>
            <div className="ad-rule">
              <label className="ad-radio"><input type="radio" name="mode" defaultChecked /> <span><b>Automatic</b> — email matched suppliers immediately</span></label>
              <label className="ad-radio"><input type="radio" name="mode" /> <span><b>Admin approves first</b> — review the matched list before sending</span></label>
              <label className="ad-radio"><input type="radio" name="mode" /> <span><b>Manual</b> — admin picks suppliers for every enquiry</span></label>
            </div>
            <div className="ad-sec-t" style={{ marginTop: 22 }}><Icon name="sliders-horizontal" size={15} /> Matching rules</div>
            <label className="sp-acc-check"><input type="checkbox" defaultChecked /> <span>Category must match the supplier’s selected categories</span></label>
            <label className="sp-acc-check"><input type="checkbox" defaultChecked /> <span>Buyer location must fall inside the supplier’s coverage area</span></label>
            <label className="sp-acc-check"><input type="checkbox" defaultChecked /> <span>Only send to verified suppliers with an active subscription</span></label>
            <label className="sp-acc-check"><input type="checkbox" /> <span>Cap at 5 suppliers per enquiry (closest first)</span></label>
            <div style={{ marginTop: 20 }}><Btn variant="primary">Save routing rules</Btn></div>
          </div>
        )}

        {tab === "cats" && <CategoryManager store={store} t={t} />}
      </div>
    </div>
  );
}

Object.assign(window, { AdminScreen });
