// Admin panel — Firebase Auth + Firestore CRUD
// Access: your-site.com/#admin  (no public link)

const FITS        = ['Athletic', 'Boxy', 'Oversized', 'Relaxed', 'Slim'];
const COLOR_OPTS  = ['black', 'cyan', 'red'];
const ACCENT_OPTS = ['cyan', 'red'];

const slugify = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');

const ainput = {
  background: 'rgba(255,255,255,0.05)',
  border: '1px solid var(--uwr-line-strong)',
  color: 'var(--uwr-off)',
  padding: '10px 12px',
  fontFamily: 'var(--uwr-mono)',
  fontSize: 12,
  width: '100%',
  boxSizing: 'border-box',
  outline: 'none',
};

const AField = ({ label, children }) => (
  <div style={{ marginBottom: 16 }}>
    <div style={{ fontFamily: 'var(--uwr-mono)', fontSize: 10, color: 'var(--uwr-off-dim)', letterSpacing: '0.08em', marginBottom: 6 }}>
      {label}
    </div>
    {children}
  </div>
);

// ── Firestore helpers ─────────────────────────────────────────────────────────
const fsaveProduct = (p)  => db.collection('products').doc(p.id).set(p);
const fdelProduct  = (id) => db.collection('products').doc(id).delete();
const fsaveCat     = (c)  => db.collection('categories').doc(c.id).set(c);
const fdelCat      = (id) => db.collection('categories').doc(id).delete();

const fseedDefaults = async () => {
  const batch = db.batch();
  DEFAULT_CATEGORIES.forEach((c) => batch.set(db.collection('categories').doc(c.id), c));
  DEFAULT_PRODUCTS.forEach((p)   => batch.set(db.collection('products').doc(p.id), p));
  await batch.commit();
};

// ── Login Form ────────────────────────────────────────────────────────────────
const AdminLogin = ({ setRoute }) => {
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error,    setError]    = React.useState('');
  const [busy,     setBusy]     = React.useState(false);

  const handleLogin = async (e) => {
    e.preventDefault();
    setBusy(true);
    setError('');
    try {
      await auth.signInWithEmailAndPassword(email, password);
    } catch (err) {
      const map = {
        'auth/user-not-found':  'Email not found.',
        'auth/wrong-password':  'Wrong password.',
        'auth/invalid-email':   'Invalid email.',
        'auth/too-many-requests': 'Too many attempts. Try later.',
      };
      setError(map[err.code] || err.message);
    }
    setBusy(false);
  };

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--uwr-black)',
    }}>
      <div style={{ width: 'min(380px, 92vw)' }}>
        <div style={{ marginBottom: 40 }}>
          <MonoTag color="var(--uwr-cyan)">// UWR/SHOP</MonoTag>
          <h1 className="uwr-head" style={{ fontSize: 40, margin: '10px 0 4px' }}>ADMIN</h1>
          <div className="uwr-mono" style={{ color: 'var(--uwr-off-dim)' }}>RESTRICTED ACCESS</div>
        </div>

        <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <AField label="EMAIL">
            <input
              style={ainput} type="email" value={email} autoFocus
              onChange={(e) => setEmail(e.target.value)}
              placeholder="admin@uwrshop.com"
            />
          </AField>
          <AField label="PASSWORD">
            <input
              style={ainput} type="password" value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
            />
          </AField>

          {error && (
            <div className="uwr-mono" style={{ color: 'var(--uwr-red)', fontSize: 11 }}>{error}</div>
          )}

          <button type="submit" disabled={busy} className="uwr-btn" style={{
            background: 'var(--uwr-cyan)', color: 'var(--uwr-black)',
            justifyContent: 'center', marginTop: 8, opacity: busy ? 0.6 : 1,
          }}>
            {busy ? 'SIGNING IN...' : 'SIGN IN'}
          </button>

          <button type="button" onClick={() => setRoute({ name: 'home' })} className="uwr-btn ghost" style={{ justifyContent: 'center' }}>
            ← BACK TO SITE
          </button>
        </form>
      </div>
    </div>
  );
};

// ── Product Drawer ────────────────────────────────────────────────────────────
const ProductDrawer = ({ product, categories, onClose }) => {
  const isNew = !product.id;
  const [form, setForm] = React.useState({
    id:       product.id       || '',
    name:     product.name     || '',
    code:     product.code     || '',
    price:    product.price    != null ? String(product.price) : '',
    color:    product.color    || 'black',
    accent:   product.accent   || '',
    category: product.category || (categories[0]?.id || ''),
    desc:     product.desc     || '',
    weight:   product.weight   || '',
    fit:      product.fit      || 'Athletic',
    fabric:   product.fabric   || '',
    sizes:    Array.isArray(product.sizes)  ? product.sizes.join(', ')  : '',
    colors:   Array.isArray(product.colors) ? product.colors.join(', ') : '',
    tag:      product.tag      || '',
    imageUrl: product.imageUrl || '',
  });
  const [busy,      setBusy]      = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const [error,     setError]     = React.useState('');
  const fileInputRef = React.useRef();

  const handleImageFile = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    // local preview immediately
    const localUrl = URL.createObjectURL(file);
    setForm((f) => ({ ...f, imageUrl: localUrl }));
    setUploading(true);
    setError('');
    try {
      const ext = file.name.split('.').pop();
      const ref = storage.ref(`products/${Date.now()}_${form.code || 'img'}.${ext}`);
      await ref.put(file, { contentType: file.type });
      const url = await ref.getDownloadURL();
      setForm((f) => ({ ...f, imageUrl: url }));
    } catch (err) {
      setError('Image upload failed: ' + err.message);
    }
    setUploading(false);
  };

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const handleSave = async () => {
    if (!form.name.trim() || !form.code.trim()) { setError('Name and code are required.'); return; }
    setBusy(true);
    setError('');
    try {
      const id = isNew ? slugify(form.name) || String(Date.now()) : form.id;
      await fsaveProduct({
        ...form,
        id,
        price:    parseFloat(form.price) || 0,
        sizes:    form.sizes.split(',').map((s) => s.trim()).filter(Boolean),
        colors:   form.colors.split(',').map((s) => s.trim()).filter(Boolean),
        tag:      form.tag.trim() || null,
        accent:   form.accent || null,
        imageUrl: form.imageUrl || null,
      });
      onClose();
    } catch (err) {
      setError(err.message);
    }
    setBusy(false);
  };

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 200, animation: 'uwrFade 0.2s ease' }} />
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 'min(540px, 96vw)',
        background: 'var(--uwr-black)', borderLeft: '1px solid var(--uwr-line-strong)',
        zIndex: 201, display: 'flex', flexDirection: 'column',
        animation: 'uwrSlideIn 0.22s cubic-bezier(.2,.7,.3,1)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '20px 24px', borderBottom: '1px solid var(--uwr-line)',
          position: 'sticky', top: 0, background: 'var(--uwr-black)', zIndex: 1,
        }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
            <span className="uwr-head" style={{ fontSize: 18 }}>{isNew ? 'ADD PRODUCT' : 'EDIT PRODUCT'}</span>
            {!isNew && <span className="uwr-mono" style={{ color: 'var(--uwr-off-dim)' }}>{form.code}</span>}
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--uwr-off)', padding: 4 }}><CloseIcon /></button>
        </div>

        <div style={{ padding: 24, flex: 1, overflowY: 'auto' }} className="uwr-no-scrollbar">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <AField label="NAME *"><input style={ainput} value={form.name} onChange={set('name')} placeholder="Forward Tee" /></AField>
            <AField label="CODE *"><input style={ainput} value={form.code} onChange={set('code')} placeholder="FWD-01" /></AField>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <AField label="PRICE (USD)"><input style={ainput} type="number" min="0" value={form.price} onChange={set('price')} placeholder="48" /></AField>
            <AField label="WEIGHT"><input style={ainput} value={form.weight} onChange={set('weight')} placeholder="240 GSM" /></AField>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
            <AField label="FIT">
              <select style={{ ...ainput, cursor: 'pointer' }} value={form.fit} onChange={set('fit')}>
                {FITS.map((f) => <option key={f} value={f} style={{ background: 'var(--uwr-black)' }}>{f}</option>)}
              </select>
            </AField>
            <AField label="IMG COLOR">
              <select style={{ ...ainput, cursor: 'pointer' }} value={form.color} onChange={set('color')}>
                {COLOR_OPTS.map((c) => <option key={c} value={c} style={{ background: 'var(--uwr-black)' }}>{c}</option>)}
              </select>
            </AField>
            <AField label="ACCENT">
              <select style={{ ...ainput, cursor: 'pointer' }} value={form.accent} onChange={set('accent')}>
                <option value="" style={{ background: 'var(--uwr-black)' }}>—</option>
                {ACCENT_OPTS.map((a) => <option key={a} value={a} style={{ background: 'var(--uwr-black)' }}>{a}</option>)}
              </select>
            </AField>
          </div>
          <AField label="CATEGORY">
            <select style={{ ...ainput, cursor: 'pointer' }} value={form.category} onChange={set('category')}>
              {categories.map((c) => <option key={c.id} value={c.id} style={{ background: 'var(--uwr-black)' }}>{c.name}</option>)}
            </select>
          </AField>
          <AField label="FABRIC"><input style={ainput} value={form.fabric} onChange={set('fabric')} placeholder="100% Heavy Cotton" /></AField>
          <AField label="DESCRIPTION">
            <textarea style={{ ...ainput, minHeight: 80, resize: 'vertical' }} value={form.desc} onChange={set('desc')} placeholder="Product description..." />
          </AField>
          <AField label="SIZES (comma-separated)"><input style={ainput} value={form.sizes} onChange={set('sizes')} placeholder="S, M, L, XL, XXL" /></AField>
          <AField label="COLORS (comma-separated)"><input style={ainput} value={form.colors} onChange={set('colors')} placeholder="Black, Off White" /></AField>
          <AField label="TAG (optional)"><input style={ainput} value={form.tag} onChange={set('tag')} placeholder="BEST SELLER / NEW" /></AField>

          {/* Image upload */}
          <AField label="PRODUCT IMAGE">
            <input ref={fileInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleImageFile} />
            {form.imageUrl ? (
              <div style={{ position: 'relative', marginBottom: 8 }}>
                <img src={form.imageUrl} alt="preview" style={{ width: '100%', height: 200, objectFit: 'cover', display: 'block' }} />
                {uploading && (
                  <div style={{
                    position: 'absolute', inset: 0, background: 'rgba(5,8,10,0.7)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <MonoTag color="var(--uwr-cyan)">UPLOADING...</MonoTag>
                  </div>
                )}
              </div>
            ) : (
              <div style={{
                height: 120, border: '1px dashed var(--uwr-line-strong)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 8,
              }}>
                <MonoTag color="var(--uwr-off-dim)">NO IMAGE</MonoTag>
              </div>
            )}
            <div style={{ display: 'flex', gap: 8 }}>
              <button
                onClick={() => fileInputRef.current.click()}
                disabled={uploading}
                className="uwr-mono"
                style={{ ...ainput, width: 'auto', cursor: 'pointer', padding: '8px 14px', opacity: uploading ? 0.5 : 1 }}
              >{uploading ? 'UPLOADING...' : form.imageUrl ? 'CHANGE IMAGE' : 'UPLOAD IMAGE'}</button>
              {form.imageUrl && !uploading && (
                <button
                  onClick={() => setForm((f) => ({ ...f, imageUrl: '' }))}
                  className="uwr-mono"
                  style={{ ...ainput, width: 'auto', cursor: 'pointer', padding: '8px 14px', color: 'var(--uwr-red)' }}
                >REMOVE</button>
              )}
            </div>
          </AField>

          {error && <div className="uwr-mono" style={{ color: 'var(--uwr-red)', marginTop: 8 }}>{error}</div>}
        </div>

        <div style={{ padding: '16px 24px', borderTop: '1px solid var(--uwr-line)', display: 'flex', gap: 12 }}>
          <button onClick={handleSave} disabled={busy} className="uwr-btn" style={{
            flex: 1, justifyContent: 'center',
            background: 'var(--uwr-cyan)', color: 'var(--uwr-black)', opacity: busy ? 0.6 : 1,
          }}>{busy ? 'SAVING...' : 'SAVE PRODUCT'}</button>
          <button onClick={onClose} className="uwr-btn ghost" style={{ flex: 1, justifyContent: 'center' }}>CANCEL</button>
        </div>
      </div>
    </>
  );
};

// ── Category Drawer ───────────────────────────────────────────────────────────
const CategoryDrawer = ({ category, onClose }) => {
  const isNew = !category.id;
  const [form, setForm] = React.useState({
    id:          category.id          || '',
    name:        category.name        || '',
    subtitle:    category.subtitle    || '',
    description: category.description || '',
    shipDate:    category.shipDate    || '',
    accent:      category.accent      || 'cyan',
  });
  const [busy,  setBusy]  = React.useState(false);
  const [error, setError] = React.useState('');

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const handleSave = async () => {
    if (!form.name.trim()) { setError('Name is required.'); return; }
    setBusy(true);
    setError('');
    try {
      const id = isNew ? slugify(form.name) || String(Date.now()) : form.id;
      await fsaveCat({ ...form, id });
      onClose();
    } catch (err) {
      setError(err.message);
    }
    setBusy(false);
  };

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 200, animation: 'uwrFade 0.2s ease' }} />
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 'min(480px, 96vw)',
        background: 'var(--uwr-black)', borderLeft: '1px solid var(--uwr-line-strong)',
        zIndex: 201, display: 'flex', flexDirection: 'column',
        animation: 'uwrSlideIn 0.22s cubic-bezier(.2,.7,.3,1)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '20px 24px', borderBottom: '1px solid var(--uwr-line)',
        }}>
          <span className="uwr-head" style={{ fontSize: 18 }}>{isNew ? 'ADD CATEGORY' : 'EDIT CATEGORY'}</span>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--uwr-off)', padding: 4 }}><CloseIcon /></button>
        </div>

        <div style={{ padding: 24, flex: 1, overflowY: 'auto' }} className="uwr-no-scrollbar">
          <AField label="NAME * (e.g. DROP 02)"><input style={ainput} value={form.name} onChange={set('name')} placeholder="DROP 02" /></AField>
          <AField label="SUBTITLE"><input style={ainput} value={form.subtitle} onChange={set('subtitle')} placeholder="ABOVE ZERO" /></AField>
          <AField label="DESCRIPTION">
            <textarea style={{ ...ainput, minHeight: 80, resize: 'vertical' }} value={form.description} onChange={set('description')} placeholder="Collection description..." />
          </AField>
          <AField label="SHIP DATE"><input style={ainput} value={form.shipDate} onChange={set('shipDate')} placeholder="12.04.2026" /></AField>
          <AField label="ACCENT COLOR">
            <select style={{ ...ainput, cursor: 'pointer' }} value={form.accent} onChange={set('accent')}>
              {ACCENT_OPTS.map((a) => <option key={a} value={a} style={{ background: 'var(--uwr-black)' }}>{a.toUpperCase()}</option>)}
            </select>
          </AField>
          {error && <div className="uwr-mono" style={{ color: 'var(--uwr-red)', marginTop: 8 }}>{error}</div>}
        </div>

        <div style={{ padding: '16px 24px', borderTop: '1px solid var(--uwr-line)', display: 'flex', gap: 12 }}>
          <button onClick={handleSave} disabled={busy} className="uwr-btn" style={{
            flex: 1, justifyContent: 'center',
            background: 'var(--uwr-cyan)', color: 'var(--uwr-black)', opacity: busy ? 0.6 : 1,
          }}>{busy ? 'SAVING...' : 'SAVE CATEGORY'}</button>
          <button onClick={onClose} className="uwr-btn ghost" style={{ flex: 1, justifyContent: 'center' }}>CANCEL</button>
        </div>
      </div>
    </>
  );
};

// ── Product Preview Modal ─────────────────────────────────────────────────────
const ProductPreviewModal = ({ product, onClose }) => {
  const accentColor = product.accent === 'red' ? 'var(--uwr-red)' : 'var(--uwr-cyan)';
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', zIndex: 400, animation: 'uwrFade 0.15s ease' }} />
      <div style={{
        position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        background: 'var(--uwr-black)', border: '1px solid var(--uwr-line-strong)',
        zIndex: 401, width: 'min(860px, 96vw)', maxHeight: '90vh',
        display: 'flex', flexDirection: 'column', animation: 'uwrFade 0.15s ease',
        overflow: 'hidden',
      }}>
        {/* header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid var(--uwr-line)' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
            <span className="uwr-head" style={{ fontSize: 16 }}>PREVIEW</span>
            <MonoTag color={accentColor}>{product.code}</MonoTag>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--uwr-off)', padding: 4 }}><CloseIcon /></button>
        </div>

        {/* content */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', overflowY: 'auto' }} className="uwr-no-scrollbar">
          {/* Left — shop card */}
          <div style={{ padding: 32, borderRight: '1px solid var(--uwr-line)' }}>
            <MonoTag color="var(--uwr-off-dim)" style={{ display: 'block', marginBottom: 16 }}>SHOP CARD</MonoTag>
            <div style={{ maxWidth: 280 }}>
              <ProductCard product={product} layout="technical" accent={product.accent || 'cyan'} onClick={() => {}} />
            </div>
          </div>

          {/* Right — product detail summary */}
          <div style={{ padding: 32 }}>
            <MonoTag color="var(--uwr-off-dim)" style={{ display: 'block', marginBottom: 16 }}>PRODUCT DETAIL</MonoTag>

            {/* Image */}
            <div style={{ width: '100%', aspectRatio: '4/3', marginBottom: 20, overflow: 'hidden' }}>
              <ProductPlaceholder
                name={product.code} color={product.color} src={product.imageUrl} hideLabel
                style={{ width: '100%', height: '100%' }}
              />
            </div>

            {product.tag && <MonoTag color={accentColor} style={{ display: 'block', marginBottom: 8 }}>★ {product.tag}</MonoTag>}
            <MonoTag color="var(--uwr-off-dim)" style={{ display: 'block', marginBottom: 4 }}>{product.code}</MonoTag>
            <div className="uwr-head" style={{ fontSize: 28, marginBottom: 4 }}>{product.name?.toUpperCase()}</div>
            <div className="uwr-head" style={{ fontSize: 20, color: accentColor, marginBottom: 16 }}>${product.price}.00</div>

            <div style={{ fontSize: 13, color: 'var(--uwr-off-dim)', lineHeight: 1.6, marginBottom: 20 }}>{product.desc}</div>

            {/* Spec table */}
            {[
              ['WEIGHT', product.weight],
              ['FIT',    product.fit?.toUpperCase()],
              ['FABRIC', product.fabric?.toUpperCase()],
              ['SIZES',  Array.isArray(product.sizes)  ? product.sizes.join(' / ')  : product.sizes],
              ['COLORS', Array.isArray(product.colors) ? product.colors.join(' / ') : product.colors],
            ].map(([k, v]) => v ? (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--uwr-line)', fontSize: 11, fontFamily: 'var(--uwr-mono)' }}>
                <span style={{ color: 'var(--uwr-off-dim)' }}>{k}</span>
                <span style={{ color: 'var(--uwr-off)' }}>{v}</span>
              </div>
            ) : null)}
          </div>
        </div>
      </div>
    </>
  );
};

// ── Confirm Dialog ────────────────────────────────────────────────────────────
const ConfirmDialog = ({ message, onConfirm, onCancel, danger }) => (
  <>
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', zIndex: 300 }} />
    <div style={{
      position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
      background: 'var(--uwr-black)', border: '1px solid var(--uwr-line-strong)',
      padding: 32, zIndex: 301, width: 'min(400px, 90vw)', animation: 'uwrFade 0.15s ease',
    }}>
      <div className="uwr-head" style={{ fontSize: 22, marginBottom: 14 }}>CONFIRM</div>
      <div className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', lineHeight: 1.6, marginBottom: 28 }}>{message}</div>
      <div style={{ display: 'flex', gap: 12 }}>
        <button onClick={onConfirm} className="uwr-btn danger" style={{ flex: 1, justifyContent: 'center' }}>
          {danger || 'DELETE'}
        </button>
        <button onClick={onCancel} className="uwr-btn ghost" style={{ flex: 1, justifyContent: 'center' }}>CANCEL</button>
      </div>
    </div>
  </>
);

// ── Admin Panel (authenticated) ───────────────────────────────────────────────
const AdminPanel = ({ user, setRoute }) => {
  const { products, categories } = useAppData();
  const [tab,          setTab]          = React.useState('products');
  const [editProduct,  setEditProduct]  = React.useState(null);
  const [editCat,      setEditCat]      = React.useState(null);
  const [previewProd,  setPreviewProd]  = React.useState(null);
  const [confirmDel,   setConfirmDel]   = React.useState(null);
  const [seeding,      setSeeding]      = React.useState(false);
  const [opError,      setOpError]      = React.useState('');

  const isEmpty = products.length === 0 && categories.length === 0;

  const execSeed = async () => {
    setSeeding(true);
    try { await fseedDefaults(); } catch (e) { setOpError(e.message); }
    setSeeding(false);
  };

  const execDelete = async () => {
    try {
      if (confirmDel.type === 'product')  await fdelProduct(confirmDel.id);
      if (confirmDel.type === 'category') await fdelCat(confirmDel.id);
    } catch (e) { setOpError(e.message); }
    setConfirmDel(null);
  };

  const tabBtn = (t, label) => (
    <button onClick={() => setTab(t)} className="uwr-head" style={{
      fontSize: 12, letterSpacing: '0.06em',
      padding: '10px 24px', background: 'transparent', border: 'none',
      borderBottom: tab === t ? '2px solid var(--uwr-cyan)' : '2px solid transparent',
      color: tab === t ? 'var(--uwr-off)' : 'var(--uwr-off-dim)',
      cursor: 'pointer',
    }}>{label}</button>
  );

  const PROD_COLS = '80px 1fr 130px 72px 100px 100px 160px';
  const CAT_COLS  = '1fr 180px 88px 110px 72px 110px';

  return (
    <div style={{ minHeight: '100vh', background: 'var(--uwr-black)' }}>
      {/* ── Header */}
      <div style={{ padding: '28px 32px 0', borderBottom: '1px solid var(--uwr-line-strong)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20, gap: 16, flexWrap: 'wrap' }}>
          <div>
            <MonoTag color="var(--uwr-cyan)">// ADMIN · {user.email}</MonoTag>
            <h1 className="uwr-head" style={{ fontSize: 'clamp(28px, 5vw, 56px)', margin: '8px 0 0', lineHeight: 0.95 }}>CONTROL PANEL</h1>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <button onClick={() => auth.signOut()} className="uwr-mono" style={{
              background: 'transparent', border: '1px solid var(--uwr-line)',
              color: 'var(--uwr-off-dim)', padding: '8px 14px', cursor: 'pointer', fontSize: 10,
            }}>SIGN OUT</button>
            <button onClick={() => setRoute({ name: 'home' })} className="uwr-btn ghost" style={{ padding: '8px 18px' }}>
              ← BACK TO SITE
            </button>
          </div>
        </div>
        <div style={{ display: 'flex' }}>
          {tabBtn('products',   `PRODUCTS (${products.length})`)}
          {tabBtn('categories', `CATEGORIES (${categories.length})`)}
        </div>
      </div>

      {opError && (
        <div style={{ padding: '12px 32px', background: 'rgba(255,59,31,0.1)', borderBottom: '1px solid var(--uwr-red)' }}>
          <span className="uwr-mono" style={{ color: 'var(--uwr-red)', fontSize: 11 }}>ERROR: {opError}</span>
          <button onClick={() => setOpError('')} className="uwr-mono" style={{ background: 'none', border: 'none', color: 'var(--uwr-red)', marginLeft: 16, cursor: 'pointer' }}>✕</button>
        </div>
      )}

      {/* ── Seed prompt */}
      {isEmpty && (
        <div style={{ padding: '48px 32px', textAlign: 'center' }}>
          <div className="uwr-head" style={{ fontSize: 28, marginBottom: 12 }}>FIRESTORE IS EMPTY</div>
          <div className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', marginBottom: 28 }}>
            NO PRODUCTS OR CATEGORIES FOUND — SEED WITH DEFAULT DATA TO GET STARTED
          </div>
          <button onClick={execSeed} disabled={seeding} className="uwr-btn" style={{
            background: 'var(--uwr-cyan)', color: 'var(--uwr-black)',
          }}>
            {seeding ? 'SEEDING...' : 'SEED DEFAULT DATA'}
          </button>
        </div>
      )}

      {/* ── Products Tab */}
      {tab === 'products' && !isEmpty && (
        <div style={{ padding: '24px 32px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <MonoTag color="var(--uwr-off-dim)">{products.length} ITEMS IN CATALOG</MonoTag>
            <button onClick={() => setEditProduct({})} className="uwr-btn" style={{ background: 'var(--uwr-cyan)', color: 'var(--uwr-black)' }}>
              + ADD PRODUCT
            </button>
          </div>

          <div style={{ border: '1px solid var(--uwr-line-strong)', overflowX: 'auto' }}>
            <div style={{
              display: 'grid', gridTemplateColumns: PROD_COLS,
              padding: '10px 20px', borderBottom: '1px solid var(--uwr-line-strong)',
              background: 'rgba(255,255,255,0.02)', minWidth: 680,
            }}>
              {['CODE', 'NAME', 'CATEGORY', 'PRICE', 'FIT', 'WEIGHT', ''].map((h) => (
                <span key={h} className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 10 }}>{h}</span>
              ))}
            </div>

            {products.length === 0 && (
              <div style={{ padding: '36px 20px', textAlign: 'center' }}>
                <MonoTag color="var(--uwr-off-dim)">NO PRODUCTS — ADD ONE ABOVE</MonoTag>
              </div>
            )}

            {products.map((p, i) => {
              const cat = categories.find((c) => c.id === p.category);
              return (
                <div key={p.id} style={{
                  display: 'grid', gridTemplateColumns: PROD_COLS,
                  padding: '14px 20px', alignItems: 'center',
                  borderBottom: i < products.length - 1 ? '1px solid var(--uwr-line)' : 'none',
                  minWidth: 680,
                }}>
                  <MonoTag color="var(--uwr-cyan)" style={{ fontSize: 11 }}>{p.code}</MonoTag>
                  <div>
                    <div className="uwr-head" style={{ fontSize: 13 }}>{p.name?.toUpperCase()}</div>
                    {p.tag && <MonoTag color="var(--uwr-off-dim)" style={{ fontSize: 9 }}>{p.tag}</MonoTag>}
                  </div>
                  <MonoTag color="var(--uwr-off-dim)" style={{ fontSize: 11 }}>{cat ? cat.name : (p.category || '—')}</MonoTag>
                  <span className="uwr-mono" style={{ color: 'var(--uwr-off)', fontSize: 13 }}>${p.price}</span>
                  <span className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 11 }}>{p.fit?.toUpperCase()}</span>
                  <span className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 11 }}>{p.weight}</span>
                  <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                    <button onClick={() => setPreviewProd(p)} className="uwr-mono" style={{
                      background: 'transparent', border: '1px solid var(--uwr-line)',
                      color: 'var(--uwr-cyan)', padding: '5px 10px', cursor: 'pointer', fontSize: 10,
                    }}>VIEW</button>
                    <button onClick={() => setEditProduct(p)} className="uwr-mono" style={{
                      background: 'transparent', border: '1px solid var(--uwr-line)',
                      color: 'var(--uwr-off-dim)', padding: '5px 10px', cursor: 'pointer', fontSize: 10,
                    }}>EDIT</button>
                    <button onClick={() => setConfirmDel({ type: 'product', id: p.id })} className="uwr-mono" style={{
                      background: 'transparent', border: '1px solid var(--uwr-line)',
                      color: 'var(--uwr-red)', padding: '5px 10px', cursor: 'pointer', fontSize: 10,
                    }}>DEL</button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ── Categories Tab */}
      {tab === 'categories' && !isEmpty && (
        <div style={{ padding: '24px 32px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <MonoTag color="var(--uwr-off-dim)">{categories.length} CATEGORIES</MonoTag>
            <button onClick={() => setEditCat({})} className="uwr-btn" style={{ background: 'var(--uwr-cyan)', color: 'var(--uwr-black)' }}>
              + ADD CATEGORY
            </button>
          </div>

          <div style={{ border: '1px solid var(--uwr-line-strong)', overflowX: 'auto' }}>
            <div style={{
              display: 'grid', gridTemplateColumns: CAT_COLS,
              padding: '10px 20px', borderBottom: '1px solid var(--uwr-line-strong)',
              background: 'rgba(255,255,255,0.02)', minWidth: 620,
            }}>
              {['NAME', 'SUBTITLE', 'ACCENT', 'SHIP DATE', 'ITEMS', ''].map((h) => (
                <span key={h} className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 10 }}>{h}</span>
              ))}
            </div>

            {categories.map((c, i) => {
              const count = products.filter((p) => p.category === c.id).length;
              const accentVar = c.accent === 'red' ? 'var(--uwr-red)' : 'var(--uwr-cyan)';
              return (
                <div key={c.id} style={{
                  display: 'grid', gridTemplateColumns: CAT_COLS,
                  padding: '16px 20px', alignItems: 'center',
                  borderBottom: i < categories.length - 1 ? '1px solid var(--uwr-line)' : 'none',
                  minWidth: 620,
                }}>
                  <div>
                    <div className="uwr-head" style={{ fontSize: 16 }}>{c.name}</div>
                    <div className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 9, marginTop: 4 }}>{c.id}</div>
                  </div>
                  <span className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 11 }}>{c.subtitle || '—'}</span>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: 8, height: 8, background: accentVar, borderRadius: '50%', flexShrink: 0 }} />
                    <span className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 10 }}>{c.accent?.toUpperCase()}</span>
                  </div>
                  <span className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', fontSize: 11 }}>{c.shipDate || '—'}</span>
                  <span className="uwr-mono" style={{ color: 'var(--uwr-off)', fontSize: 14 }}>{count}</span>
                  <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                    <button onClick={() => setEditCat(c)} className="uwr-mono" style={{
                      background: 'transparent', border: '1px solid var(--uwr-line)',
                      color: 'var(--uwr-off-dim)', padding: '5px 10px', cursor: 'pointer', fontSize: 10,
                    }}>EDIT</button>
                    <button
                      disabled={categories.length <= 1}
                      onClick={() => categories.length > 1 && setConfirmDel({ type: 'category', id: c.id })}
                      className="uwr-mono"
                      style={{
                        background: 'transparent', border: '1px solid var(--uwr-line)',
                        color: categories.length <= 1 ? 'var(--uwr-line-strong)' : 'var(--uwr-red)',
                        padding: '5px 10px', cursor: categories.length <= 1 ? 'not-allowed' : 'pointer', fontSize: 10,
                      }}
                    >DEL</button>
                  </div>
                </div>
              );
            })}
          </div>

          <div className="uwr-mono" style={{ color: 'var(--uwr-off-dim)', marginTop: 14, fontSize: 10 }}>
            ASSIGN PRODUCTS TO CATEGORIES VIA THE PRODUCTS TAB
          </div>
        </div>
      )}

      {/* ── Drawers */}
      {editProduct !== null && (
        <ProductDrawer product={editProduct} categories={categories} onClose={() => setEditProduct(null)} />
      )}
      {editCat !== null && (
        <CategoryDrawer category={editCat} onClose={() => setEditCat(null)} />
      )}

      {/* ── Preview Modal */}
      {previewProd && (
        <ProductPreviewModal product={previewProd} onClose={() => setPreviewProd(null)} />
      )}

      {/* ── Confirm Dialog */}
      {confirmDel && (
        <ConfirmDialog
          message={
            confirmDel.type === 'product'
              ? 'Delete this product? This cannot be undone.'
              : 'Delete this category? Products assigned to it will become uncategorized.'
          }
          onConfirm={execDelete}
          onCancel={() => setConfirmDel(null)}
        />
      )}
    </div>
  );
};

// ── Admin Page (auth gate) ────────────────────────────────────────────────────
const AdminPage = ({ setRoute }) => {
  const [user,        setUser]        = React.useState(undefined); // undefined = loading
  const [authChecked, setAuthChecked] = React.useState(false);

  React.useEffect(() => {
    const unsub = auth.onAuthStateChanged((u) => {
      setUser(u);
      setAuthChecked(true);
    });
    return unsub;
  }, []);

  if (!authChecked) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--uwr-black)' }}>
        <MonoTag color="var(--uwr-cyan)">CHECKING AUTH...</MonoTag>
      </div>
    );
  }

  if (!user) return <AdminLogin setRoute={setRoute} />;

  return <AdminPanel user={user} setRoute={setRoute} />;
};

Object.assign(window, { AdminPage });
