/* global React, Icon, MLN */
const { useState: useStateAdm, useEffect: useEffectAdm, useRef: useRefAdm } = React;

const admInput = {
  fontFamily: 'var(--font-body)', fontSize: 15, padding: '10px 12px', borderRadius: 'var(--radius-sm)',
  border: '1.5px solid var(--border)', background: 'var(--white)', color: 'var(--ink-900)',
  outline: 'none', width: '100%', boxSizing: 'border-box',
};
const admBtn = {
  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14.5, border: 'none', cursor: 'pointer',
  padding: '10px 18px', borderRadius: 'var(--radius-pill)', display: 'inline-flex', alignItems: 'center', gap: 8,
};
const admGhost = { ...admBtn, background: 'var(--white)', color: 'var(--brand)', border: '1.5px solid var(--red-200)' };
const admDanger = { background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-300)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: 8, borderRadius: 'var(--radius-sm)' };
const admLabel = { display: 'block', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12.5, color: 'var(--ink-500)', marginBottom: 5 };

// Allowed image types/size — shared by all uploads (product, testimonial, gallery)
const IMG_ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
const IMG_MAX_MB = 5;

// Returns an error message if the file is not an allowed image, otherwise null.
function imageFileError(file) {
  if (!file) return 'לא נבחר קובץ';
  if (!IMG_ALLOWED_TYPES.includes(file.type)) return 'סוג קובץ לא נתמך. מותר: JPG, PNG, WebP, GIF';
  if (file.size > IMG_MAX_MB * 1024 * 1024) return `הקובץ גדול מדי (מקסימום ${IMG_MAX_MB}MB)`;
  return null;
}

// Validates type+size before reading. On invalid file calls onError(msg) (defaults to alert).
function readImageFile(file, cb, onError) {
  const err = imageFileError(file);
  if (err) { (onError || ((m) => alert(m)))(err); return; }
  const r = new FileReader();
  r.onload = () => cb(r.result);
  r.readAsDataURL(file);
}

// ---------- Login gate ----------
const AdminLogin = ({ onAuth, onClose, data }) => {
  const [email, setEmail] = useStateAdm('');
  const [pass, setPass] = useStateAdm('');
  const [err, setErr] = useStateAdm('');
  const [busy, setBusy] = useStateAdm(false);
  const [show, setShow] = useStateAdm(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    if (!window.MLN_AUTH || !window.MLN_AUTH.available) { setErr('אין חיבור לשרת — בדוק אינטרנט ונסה שוב'); return; }
    setBusy(true);
    try {
      await window.MLN_AUTH.signIn(email.trim(), pass);
      onAuth();
    } catch (ex) {
      setErr('שם משתמש או סיסמה שגויים');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ width: 'min(420px, 100%)', background: 'var(--paper)', borderRadius: 'var(--radius-xl)', padding: 'clamp(28px,4vw,42px)', boxShadow: '0 40px 100px rgba(74,14,24,0.4)', position: 'relative', animation: 'mlnPop 320ms var(--ease-out)' }}>
      <button onClick={onClose} aria-label="סגירה" style={{ position: 'absolute', top: 16, left: 16, width: 36, height: 36, borderRadius: '50%', border: '1px solid var(--border)', background: 'var(--white)', color: 'var(--ink-500)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="x" size={20} /></button>
      <div style={{ width: 60, height: 60, borderRadius: 18, background: 'var(--surface-tint)', color: 'var(--brand)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}><Icon name="lock" size={28} /></div>
      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, textAlign: 'center', margin: '0 0 6px', color: 'var(--ink-900)' }}>אזור ניהול</h3>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, textAlign: 'center', color: 'var(--ink-500)', margin: '0 0 24px' }}>אנא הזן שם משתמש וסיסמה</p>
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <input type="text" autoFocus value={email} onChange={e => { setEmail(e.target.value); setErr(''); }} placeholder="שם משתמש" style={{ ...admInput, padding: '13px 14px', borderColor: err ? 'var(--brand)' : 'var(--border)' }} />
        <div style={{ position: 'relative' }}>
          <input type={show ? 'text' : 'password'} value={pass} onChange={e => { setPass(e.target.value); setErr(''); }} placeholder="סיסמה" style={{ ...admInput, padding: '13px 14px', borderColor: err ? 'var(--brand)' : 'var(--border)' }} />
          <button type="button" onClick={() => setShow(s => !s)} aria-label="הצג סיסמה" style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-300)', padding: 6 }}><Icon name="eye" size={18} /></button>
        </div>
        {err && <span style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--brand)', textAlign: 'center' }}>{err}</span>}
        <button type="submit" disabled={busy} style={{ ...admBtn, background: 'var(--brand)', color: '#fff', justifyContent: 'center', padding: '13px', fontSize: 16, boxShadow: 'var(--shadow-red)', opacity: busy ? 0.7 : 1, cursor: busy ? 'wait' : 'pointer' }}>{busy ? 'מתחבר…' : 'כניסה'}</button>
      </form>
    </div>
  );
};

// ---------- Store management ----------
const StoreAdmin = ({ data, onChange }) => {
  const imgRefs = useRefAdm({});
  const upd = (id, patch) => onChange({ ...data, products: data.products.map(p => p.id === id ? { ...p, ...patch } : p) });
  const softDel = (p) => {
    if (!confirm('להעביר למחק לסל?')) return;
    onChange({ ...data,
      products: data.products.filter(x => x.id !== p.id),
      trash: [{ ...p, _section: 'products', _deletedAt: new Date().toISOString() }, ...(data.trash || [])],
    });
  };
  const add = () => onChange({ ...data, products: [...data.products, {
    id: MLN.id(), icon: 'cart', name: 'מוצר חדש', price: 0, order: 'cart',
    stock: 0, active: true, status: 'active', statusLabel: '', hidePrice: false, image: null,
    desc: 'תיאור המוצר', note: '',
  }] });

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: 0 }}>שינוי מחירים, מלאי, תיאור, תמונה והוספת מוצרים.</p>
        <button onClick={add} style={{ ...admBtn, background: 'var(--brand)', color: '#fff' }}><Icon name="plus" size={17} /> מוצר חדש</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {data.products.map(p => (
          <div key={p.id} style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: 18, boxShadow: 'var(--shadow-sm)' }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 12, background: 'var(--surface-tint)', color: 'var(--brand)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                  {p.image ? <img src={p.image} style={{ width: '100%', height: '100%', objectFit: 'cover' }} alt="" /> : <Icon name={p.icon} size={20} />}
                </div>
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13.5, color: p.active ? 'var(--brand)' : 'var(--ink-300)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={p.active} onChange={e => upd(p.id, { active: e.target.checked })} /> {p.active ? 'מוצג בחנות' : 'מוסתר'}
                </label>
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--ink-500)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={!!p.hidePrice} onChange={e => upd(p.id, { hidePrice: e.target.checked })} /> הסתר מחיר
                </label>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <input type="file" accept="image/*" style={{ display: 'none' }} ref={el => imgRefs.current[p.id] = el} onChange={e => e.target.files[0] && readImageFile(e.target.files[0], src => upd(p.id, { image: src }))} />
                <button onClick={() => imgRefs.current[p.id] && imgRefs.current[p.id].click()} style={{ ...admGhost, fontSize: 13, padding: '7px 12px' }}><Icon name="image" size={14} /> תמונה</button>
                {p.image && <button onClick={() => upd(p.id, { image: null })} style={{ ...admGhost, fontSize: 12, padding: '7px 10px', color: 'var(--ink-400)' }}>הסר תמונה</button>}
                <button onClick={() => softDel(p)} title="העבר לסל" style={admDanger} onMouseEnter={e => e.currentTarget.style.color = 'var(--brand)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-300)'}><Icon name="trash" size={18} /></button>
              </div>
            </div>

            {/* Product image preview */}
            {p.image && (
              <div style={{ marginBottom: 12, borderRadius: 'var(--radius-md)', overflow: 'hidden', height: 100, background: 'var(--cream)' }}>
                <img src={p.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
            )}

            {/* Fields */}
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1.3fr', gap: 12 }} className="mln-adm-prod mln-adm-prod-fields">
              <div><span style={admLabel}>שם המוצר</span><input value={p.name} onChange={e => upd(p.id, { name: e.target.value })} style={admInput} /></div>
              <div><span style={admLabel}>מחיר (₪)</span><input type="number" min="0" value={p.price} onChange={e => upd(p.id, { price: Number(e.target.value) })} style={admInput} /></div>
              <div><span style={admLabel}>מלאי</span><input type="number" min="0" value={p.stock === null ? '' : p.stock} placeholder="ללא" onChange={e => upd(p.id, { stock: e.target.value === '' ? null : Number(e.target.value) })} style={admInput} /></div>
              <div><span style={admLabel}>סוג הזמנה</span>
                <select value={p.order} onChange={e => upd(p.id, { order: e.target.value })} style={admInput}>
                  <option value="cart">הזמנה רגילה</option>
                  <option value="manual">ידנית (טלפון/מייל)</option>
                </select>
              </div>
            </div>
            <div style={{ marginTop: 12 }}><span style={admLabel}>תיאור</span><textarea value={p.desc} rows={2} onChange={e => upd(p.id, { desc: e.target.value })} style={{ ...admInput, resize: 'vertical' }} /></div>
            <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <span style={admLabel}>סטטוס זמינות</span>
                <select value={p.status || 'active'} onChange={e => upd(p.id, { status: e.target.value })} style={admInput}>
                  <option value="active">✅ זמין</option>
                  <option value="out-of-stock">🔴 אזל המלאי</option>
                  <option value="coming-soon">⏳ בקרוב</option>
                  <option value="custom">✏️ הודעה מותאמת</option>
                </select>
              </div>
              {p.status === 'custom' && (
                <div>
                  <span style={admLabel}>טקסט מותאם</span>
                  <input value={p.statusLabel || ''} placeholder="לדוגמה: נגמר לזמנית..." onChange={e => upd(p.id, { statusLabel: e.target.value })} style={admInput} />
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---------- Gallery management ----------
const GalleryAdmin = ({ data, onChange }) => {
  const fileRef = useRefAdm(null);
  const onFiles = (files) => {
    const arr = Array.from(files || []);
    const invalid = arr.filter(f => imageFileError(f) !== null);
    if (invalid.length > 0) {
      alert(`קבצים לא תקינים: גודל מקסימלי ${IMG_MAX_MB}MB, סוגים מותרים: JPG, PNG, WebP, GIF`);
      return;
    }
    let pending = arr.length;
    const next = [];
    arr.forEach(f => readImageFile(f, (src) => {
      next.push({ id: MLN.id(), src, caption: '' });
      if (--pending === 0) onChange({ ...data, gallery: [...next, ...data.gallery] });
    }));
  };
  const softDel = (g) => onChange({
    ...data,
    gallery: data.gallery.filter(x => x.id !== g.id),
    trash: [{ ...g, _section: 'gallery', _deletedAt: new Date().toISOString() }, ...(data.trash || [])],
  });
  const cap = (id, caption) => onChange({ ...data, gallery: data.gallery.map(g => g.id === id ? { ...g, caption } : g) });
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: 0 }}>העלאת תמונות חדשות. מחיקה שולחת לסל.</p>
        <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={e => onFiles(e.target.files)} />
        <button onClick={() => fileRef.current && fileRef.current.click()} style={{ ...admBtn, background: 'var(--brand)', color: '#fff' }}><Icon name="upload" size={17} /> העלאת תמונה</button>
      </div>
      {data.gallery.length === 0 ? (
        <div style={{ textAlign: 'center', color: 'var(--ink-400)', fontFamily: 'var(--font-body)', padding: '36px 0', border: '1.5px dashed var(--border)', borderRadius: 'var(--radius-lg)' }}>אין עדיין תמונות.</div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 16 }}>
          {data.gallery.map(g => (
            <div key={g.id} style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', overflow: 'hidden', boxShadow: 'var(--shadow-sm)' }}>
              <div style={{ position: 'relative', aspectRatio: '4/3', background: 'var(--red-100)' }}>
                <img src={g.src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                <button onClick={() => softDel(g)} title="לסל" style={{ position: 'absolute', top: 8, left: 8, width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'rgba(36,8,14,0.62)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="trash" size={16} /></button>
              </div>
              <input value={g.caption} placeholder="כיתוב…" onChange={e => cap(g.id, e.target.value)} style={{ ...admInput, border: 'none', borderTop: '1px solid var(--border)', borderRadius: 0, fontSize: 13.5 }} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ---------- Testimonials management ----------
const TestimonialsAdmin = ({ data, onChange }) => {
  const fileRefs = useRefAdm({});
  const upd = (id, patch) => onChange({ ...data, testimonials: data.testimonials.map(t => t.id === id ? { ...t, ...patch } : t) });
  const softDel = (t) => onChange({
    ...data,
    testimonials: data.testimonials.filter(x => x.id !== t.id),
    trash: [{ ...t, _section: 'testimonials', _deletedAt: new Date().toISOString() }, ...(data.trash || [])],
  });
  const add = () => onChange({ ...data, testimonials: [{ id: MLN.id(), name: 'שם הממליץ/ה', role: '', text: 'תוכן ההמלצה', img: null }, ...data.testimonials] });
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: 0 }}>הוספה ועריכה של המלצות. מחיקה שולחת לסל.</p>
        <button onClick={add} style={{ ...admBtn, background: 'var(--brand)', color: '#fff' }}><Icon name="plus" size={17} /> המלצה חדשה</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {data.testimonials.map(t => (
          <div key={t.id} style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: 18, boxShadow: 'var(--shadow-sm)', display: 'flex', gap: 16 }}>
            <div style={{ flexShrink: 0, textAlign: 'center' }}>
              <div style={{ width: 64, height: 64, borderRadius: '50%', overflow: 'hidden', background: 'var(--red-200)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--brand)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, marginBottom: 8 }}>
                {t.img ? <img src={t.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : (t.name || '?').trim().charAt(0)}
              </div>
              <input type="file" accept="image/*" capture="environment" style={{ display: 'none' }} ref={el => fileRefs.current[t.id] = el} onChange={e => e.target.files[0] && readImageFile(e.target.files[0], src => upd(t.id, { img: src }))} />
              <button onClick={() => fileRefs.current[t.id] && fileRefs.current[t.id].click()} style={{ background: 'var(--surface-tint)', border: '1px solid var(--red-200)', borderRadius: 'var(--radius-sm)', cursor: 'pointer', color: 'var(--brand)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12, padding: '5px 8px', display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="upload" size={13} /> תמונה</button>
              {t.img && <button onClick={() => upd(t.id, { img: null })} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-300)', fontFamily: 'var(--font-body)', fontSize: 11, marginTop: 3 }}>הסר</button>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', gap: 12, marginBottom: 10 }}>
                <div style={{ flex: 1 }}><span style={admLabel}>שם</span><input value={t.name} onChange={e => upd(t.id, { name: e.target.value })} style={admInput} /></div>
                <div style={{ flex: 1 }}><span style={admLabel}>תפקיד / הקשר</span><input value={t.role || ''} onChange={e => upd(t.id, { role: e.target.value })} style={admInput} /></div>
                <button onClick={() => softDel(t)} title="לסל" style={{ ...admDanger, alignSelf: 'flex-end', marginBottom: 2 }} onMouseEnter={e => e.currentTarget.style.color = 'var(--brand)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-300)'}><Icon name="trash" size={18} /></button>
              </div>
              <span style={admLabel}>תוכן ההמלצה</span><textarea value={t.text} rows={2} onChange={e => upd(t.id, { text: e.target.value })} style={{ ...admInput, resize: 'vertical' }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---------- Inbox (reads from Supabase — מוגן ב‑RLS) ----------
const InboxAdmin = ({ items, loading, error, onRefresh }) => {
  const [filter, setFilter] = useStateAdm('all');
  const [busyId, setBusyId] = useStateAdm(null);

  const fmt = (iso) => { try { return new Date(iso).toLocaleString('he-IL', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; } };
  const composeLecture = (m) => [
    m.city ? 'עיר: ' + m.city : '',
    m.address ? 'כתובת: ' + m.address : '',
    (m.date_1 || m.date_2) ? 'תאריך: ' + [m.date_1, m.date_2].filter(Boolean).join(' / ') : '',
    m.preferred_time ? 'שעה: ' + m.preferred_time : '',
    m.audience_type ? 'קהל: ' + m.audience_type : '',
    m.organization ? 'ארגון: ' + m.organization : '',
    m.notes ? '\nהערות: ' + m.notes : '',
  ].filter(Boolean).join('\n');

  const rowKey = (m) => m._table + ':' + m.id;
  const markRead = async (m, read) => {
    setBusyId(rowKey(m));
    try { await window.MLN_AUTH.setRead(m._table, m.id, read); onRefresh(); }
    catch (e) { alert('עדכון נכשל: ' + (e.message || '')); }
    finally { setBusyId(null); }
  };
  const del = async (m) => {
    if (!confirm('למחוק פנייה זו לצמיתות? לא ניתן לשחזר.')) return;
    setBusyId(rowKey(m));
    try { await window.MLN_AUTH.remove(m._table, m.id); onRefresh(); }
    catch (e) { alert('מחיקה נכשלה: ' + (e.message || '')); }
    finally { setBusyId(null); }
  };

  const kindOf = (m) => {
    if (m._kind === 'lecture') return 'lecture';
    const s = (m.subject || '').trim();
    if (s.includes('ספר'))   return 'book';
    if (s.includes('מוצר') || s.includes('קלפ') || s.includes('שיר') || s.includes('הזמנ')) return 'product';
    return 'general';
  };
  const counts = { all: items.length, lecture: 0, book: 0, product: 0, general: 0 };
  items.forEach(m => { counts[kindOf(m)] = (counts[kindOf(m)] || 0) + 1; });
  const list = filter === 'all' ? items : items.filter(m => kindOf(m) === filter);

  const FILTERS = [
    { id: 'all',     label: 'הכל' },
    { id: 'lecture', label: 'הרצאות' },
    { id: 'book',    label: 'הזמנות ספר' },
    { id: 'product', label: 'הזמנות מוצרים' },
    { id: 'general', label: 'פניות כלליות' },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: 0 }}>כל הפניות מהאתר — נטענות מהשרת בצורה מאובטחת.</p>
        <button onClick={onRefresh} disabled={loading} style={{ ...admGhost, fontSize: 13 }}><Icon name="gear" size={15} /> {loading ? 'טוען…' : 'רענון'}</button>
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20 }}>
        {FILTERS.map(f => counts[f.id] > 0 || f.id === 'all' ? (
          <button key={f.id} onClick={() => setFilter(f.id)} style={chip(filter === f.id)}>
            {f.label} ({counts[f.id] || 0})
          </button>
        ) : null)}
      </div>

      {error ? (
        <div style={{ textAlign: 'center', color: 'var(--brand)', fontFamily: 'var(--font-body)', padding: '36px 18px', border: '1.5px dashed var(--red-200)', borderRadius: 'var(--radius-lg)' }}>
          שגיאה בטעינת הפניות: {error}<br /><span style={{ fontSize: 13, color: 'var(--ink-400)' }}>ודאי שהשלמת את הגדרות האבטחה ב‑Supabase (ראי SECURITY-SETUP.md).</span>
        </div>
      ) : loading ? (
        <div style={{ textAlign: 'center', color: 'var(--ink-400)', fontFamily: 'var(--font-body)', padding: '48px 0' }}>טוען פניות…</div>
      ) : list.length === 0 ? (
        <div style={{ textAlign: 'center', color: 'var(--ink-400)', fontFamily: 'var(--font-body)', padding: '48px 0', border: '1.5px dashed var(--border)', borderRadius: 'var(--radius-lg)' }}>
          <Icon name="inbox" size={34} style={{ opacity: 0.4 }} /><div style={{ marginTop: 10 }}>אין פניות להצגה.</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {list.map(m => {
            const isLecture = m._kind === 'lecture';
            const mk = kindOf(m);
            const label = isLecture ? 'הזמנת הרצאה'
              : mk === 'book'    ? 'הזמנת ספר'
              : mk === 'product' ? (m.subject || 'הזמנת מוצר')
              : (m.subject || 'פנייה כללית');
            const color = isLecture ? '#B11E33' : mk === 'book' ? '#8E1B2E' : mk === 'product' ? '#C8324A' : '#7A6A67';
            const body = isLecture ? composeLecture(m) : (m.message || '');
            const replyTo = m.email || MLN.EMAIL;
            const replySubject = '[' + label + '] תשובה לפנייתך';
            const rowBusy = busyId === rowKey(m);
            return (
              <div key={rowKey(m)} style={{ background: m.read ? 'var(--white)' : 'var(--surface-tint)', border: '1px solid ' + (m.read ? 'var(--border)' : 'var(--red-200)'), borderRadius: 'var(--radius-lg)', padding: 18, boxShadow: 'var(--shadow-sm)', opacity: rowBusy ? 0.6 : 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 10, flexWrap: 'wrap' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ background: color, color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, padding: '4px 11px', borderRadius: 'var(--radius-pill)' }}>{label}</span>
                    {!m.read && <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--brand)' }} />}
                  </div>
                  <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--ink-400)' }}>{fmt(m.created_at)}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--ink-900)', marginBottom: 4 }}>{m.name || '(ללא שם)'}</div>
                <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-500)', marginBottom: 10 }}>
                  {m.phone && <a href={'tel:' + m.phone} style={{ color: 'var(--brand)', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="phone" size={14} /> {m.phone}</a>}
                  {m.email && <a href={MLN.gmailTo(m.email)} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--brand)', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="mail" size={14} /> {m.email}</a>}
                </div>
                {body && <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.65, color: 'var(--ink-700)', margin: '0 0 14px', background: 'var(--paper)', padding: '12px 14px', borderRadius: 'var(--radius-md)', whiteSpace: 'pre-wrap' }}>{body}</p>}
                <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                  <button onClick={() => window.open(MLN.gmailTo(replyTo, replySubject), '_blank')} style={admGhost}><Icon name="mail" size={15} /> מענה</button>
                  <button onClick={() => markRead(m, !m.read)} disabled={rowBusy} style={admGhost}><Icon name="check" size={15} /> {m.read ? 'סמן כלא נקרא' : 'סמן כנקרא'}</button>
                  <button onClick={() => del(m)} disabled={rowBusy} style={{ ...admGhost, color: 'var(--ink-500)', borderColor: 'var(--border)' }}><Icon name="trash" size={15} /> מחיקה</button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// ---------- Trash bin ----------
const TrashAdmin = ({ data, onChange }) => {
  const trash = data.trash || [];
  const restore = (item) => {
    const { _section, _deletedAt, ...original } = item;
    const section = _section || 'inbox';
    const updated = [...(data[section] || []), original];
    onChange({ ...data, [section]: updated, trash: trash.filter(x => x.id !== item.id) });
  };
  const permDelete = (item) => {
    if (!confirm('למחוק לצמיתות? לא ניתן לשחזר.')) return;
    onChange({ ...data, trash: trash.filter(x => x.id !== item.id) });
  };
  const sectionLabel = { inbox: 'תיבת פניות', gallery: 'גלריה', testimonials: 'המלצות', products: 'חנות' };
  const fmt = (iso) => { try { return new Date(iso).toLocaleString('he-IL', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; } };

  return (
    <div>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: '0 0 16px' }}>פריטים שנמחקו — ניתן לשחזר או למחוק לצמיתות.</p>
      {trash.length === 0 ? (
        <div style={{ textAlign: 'center', color: 'var(--ink-400)', fontFamily: 'var(--font-body)', padding: '48px 0', border: '1.5px dashed var(--border)', borderRadius: 'var(--radius-lg)' }}>
          <Icon name="trash" size={34} style={{ opacity: 0.3 }} /><div style={{ marginTop: 10 }}>הסל ריק.</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[...trash].sort((a, b) => new Date(b._deletedAt) - new Date(a._deletedAt)).map(item => (
            <div key={item.id} style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
              <div>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--ink-900)' }}>
                  {item.name || item.caption || item.text?.slice(0, 40) || '(ללא שם)'}
                </span>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--ink-400)', marginTop: 3 }}>
                  {sectionLabel[item._section] || item._section} · נמחק: {fmt(item._deletedAt)}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={() => restore(item)} style={{ ...admGhost, fontSize: 13 }}>שחזור</button>
                <button onClick={() => permDelete(item)} style={{ ...admGhost, fontSize: 13, color: 'var(--brand)', borderColor: 'var(--red-200)' }}>מחיקה לצמיתות</button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ---------- Poem editor ----------
const PoemAdmin = ({ data, onChange }) => {
  const poem = data.poem || { lines: '', source: 'מתוך הספר' };
  const upd = (patch) => onChange({ ...data, poem: { ...poem, ...patch } });
  return (
    <div style={{ maxWidth: 620 }}>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: '0 0 22px' }}>
        כל שורה בשורה נפרדת. השורה האחרונה תודגש בזהב.
      </p>
      <div style={{ marginBottom: 18 }}>
        <span style={admLabel}>שורות השיר</span>
        <textarea value={poem.lines} rows={6} onChange={e => upd({ lines: e.target.value })}
          style={{ ...admInput, resize: 'vertical', fontFamily: 'var(--font-poem)', fontSize: 18, lineHeight: 1.9, direction: 'rtl' }}
          placeholder={'שורה ראשונה\nשורה שנייה\nשורה אחרונה (תודגש בזהב)'} />
      </div>
      <div>
        <span style={admLabel}>מקור / ייחוס</span>
        <input value={poem.source} onChange={e => upd({ source: e.target.value })} style={admInput} placeholder="מתוך הספר" />
      </div>
      <div style={{ marginTop: 22, background: 'linear-gradient(165deg, #7E0A1D, #2A0610)', borderRadius: 'var(--radius-lg)', padding: '24px 28px', textAlign: 'center' }}>
        <p style={{ fontFamily: 'var(--font-poem)', fontSize: 'clamp(1.1rem, 2vw, 1.4rem)', lineHeight: 1.8, color: '#fff', margin: '0 0 12px' }}>
          {(poem.lines || '').split('\n').map((line, i, arr) => (
            <React.Fragment key={i}>
              <span style={i === arr.length - 1 ? { color: '#D4AF7A' } : {}}>{line}</span>
              {i < arr.length - 1 && <br />}
            </React.Fragment>
          ))}
        </p>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'rgba(255,246,242,0.6)', letterSpacing: '0.18em' }}>— {poem.source}</div>
      </div>
    </div>
  );
};

// ---------- About editor ----------
const AboutAdmin = ({ data, onChange }) => {
  const about = data.about || { title: '', paragraphs: ['', '', ''] };
  const updTitle = (v) => onChange({ ...data, about: { ...about, title: v } });
  const updPara = (i, v) => {
    const p = [...about.paragraphs];
    p[i] = v;
    onChange({ ...data, about: { ...about, paragraphs: p } });
  };
  const addPara = () => onChange({ ...data, about: { ...about, paragraphs: [...about.paragraphs, ''] } });
  const delPara = (i) => {
    const p = about.paragraphs.filter((_, idx) => idx !== i);
    onChange({ ...data, about: { ...about, paragraphs: p } });
  };

  return (
    <div style={{ maxWidth: 680 }}>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-500)', margin: '0 0 22px' }}>
        עריכת טקסט "מי אני" — הכותרת והפסקאות.
      </p>
      <div style={{ marginBottom: 18 }}>
        <span style={admLabel}>כותרת (שורות מופרדות בשבירת שורה)</span>
        <textarea value={about.title} rows={2} onChange={e => updTitle(e.target.value)}
          style={{ ...admInput, resize: 'vertical', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }} />
      </div>
      <span style={admLabel}>פסקאות הסיפור</span>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 6 }}>
        {about.paragraphs.map((p, i) => (
          <div key={i} style={{ position: 'relative' }}>
            <textarea value={p} rows={3} onChange={e => updPara(i, e.target.value)}
              style={{ ...admInput, resize: 'vertical', paddingLeft: 38 }}
              placeholder={`פסקה ${i + 1}`} />
            {about.paragraphs.length > 1 && (
              <button onClick={() => delPara(i)} style={{ position: 'absolute', top: 8, left: 8, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-300)', fontSize: 18, lineHeight: 1 }}>×</button>
            )}
          </div>
        ))}
        <button onClick={addPara} style={{ ...admGhost, alignSelf: 'flex-start' }}><Icon name="plus" size={15} /> הוסף פסקה</button>
      </div>
    </div>
  );
};

// ---------- Invoice generator ----------
const InvoiceAdmin = ({ data, onChange }) => {
  const inv = data.invoice || { businessName: '', businessAddress: '', businessId: '', vatNumber: '', logo: null, nextInvoiceNum: 1, vatPercent: 17 };
  const updInv = (patch) => onChange({ ...data, invoice: { ...inv, ...patch } });

  const [form, setForm] = useStateAdm({ customerName: '', description: '', amount: '', date: new Date().toISOString().slice(0, 10) });
  const [preview, setPreview] = useStateAdm(null);
  const [recipients, setRecipients] = useStateAdm(inv.defaultRecipients || MLN.EMAIL);
  const [sendStatus, setSendStatus] = useStateAdm(null); // null | 'sending' | 'ok' | 'err'
  const [remoteInvoices, setRemoteInvoices] = useStateAdm(null); // null = טרם נטען
  const logoRef = useRefAdm(null);
  const canvasRef = useRefAdm(null);

  // טעינת חשבוניות מ-Supabase בכניסה לטאב
  useEffectAdm(() => {
    if (!window.MLN_INVOICES) return;
    window.MLN_INVOICES.fetch().then(({ items, error }) => {
      if (!error) setRemoteInvoices(items);
    });
  }, []);

  const total = +(parseFloat(form.amount) || 0).toFixed(2);
  const amountNum = +(total / (1 + inv.vatPercent / 100)).toFixed(2);  // net לפני מע"מ
  const vatAmount = +(total - amountNum).toFixed(2);
  const archive = remoteInvoices !== null ? remoteInvoices : (data.invoices || []);

  // בונה רשומת חשבונית מתוך הטופס הנוכחי (שדות בלבד — לא תמונה).
  // amount = net לפני מע"מ; total = הסכום שהמשתמש הזין (כולל מע"מ).
  const buildRecord = () => ({
    id: MLN.id(),
    num: inv.nextInvoiceNum,
    date: form.date,
    customerName: form.customerName,
    clientName: form.customerName,
    clientEmail: recipients,
    description: form.description,
    amount: amountNum,
    vat: vatAmount,
    vatPercent: inv.vatPercent,
    total: total,
    businessName: inv.businessName || '',
    recipients: recipients,
    createdAt: new Date().toISOString(),
  });

  // מצייר חשבונית על הקנבס מתוך רשומה ומחזיר תמונת PNG (dataURL).
  // פרטי העסק הקבועים (כתובת/ח.פ/עוסק) נלקחים מההגדרות הנוכחיות (inv).
  const drawInvoice = (rec) => {
    const canvas = canvasRef.current;
    if (!canvas) return null;
    const ctx = canvas.getContext('2d');
    canvas.width = 794; canvas.height = 1123;  // A4 at 96dpi

    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Border
    ctx.strokeStyle = '#C8102E'; ctx.lineWidth = 6;
    ctx.strokeRect(20, 20, canvas.width - 40, canvas.height - 40);

    // Header band
    ctx.fillStyle = '#C8102E';
    ctx.fillRect(20, 20, canvas.width - 40, 80);

    ctx.fillStyle = '#FFFFFF';
    ctx.font = 'bold 28px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('חשבונית מס', canvas.width / 2, 68);

    // Business name
    ctx.fillStyle = '#1C1C1C';
    ctx.font = 'bold 22px Arial';
    ctx.textAlign = 'right';
    ctx.fillText(rec.businessName || inv.businessName || 'שם העסק', canvas.width - 50, 145);

    ctx.font = '16px Arial';
    ctx.fillStyle = '#6B6B6B';
    ctx.fillText(inv.businessAddress || '', canvas.width - 50, 168);
    if (inv.businessId) ctx.fillText('ח.פ / ע.מ: ' + inv.businessId, canvas.width - 50, 190);
    if (inv.vatNumber) ctx.fillText('עוסק מורשה: ' + inv.vatNumber, canvas.width - 50, 212);

    // Invoice number + date
    ctx.fillStyle = '#1C1C1C';
    ctx.font = 'bold 16px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('מספר חשבונית: ' + rec.num, 50, 145);
    ctx.font = '15px Arial';
    ctx.fillStyle = '#6B6B6B';
    ctx.fillText('תאריך: ' + String(rec.date).split('-').reverse().join('/'), 50, 168);

    // Divider
    ctx.strokeStyle = '#ECE4DB'; ctx.lineWidth = 1;
    ctx.beginPath(); ctx.moveTo(50, 240); ctx.lineTo(canvas.width - 50, 240); ctx.stroke();

    // Customer
    ctx.fillStyle = '#1C1C1C'; ctx.font = 'bold 16px Arial'; ctx.textAlign = 'right';
    ctx.fillText('לכבוד: ' + (rec.customerName || ''), canvas.width - 50, 275);

    // Table header
    ctx.fillStyle = '#F6EFE7';
    ctx.fillRect(50, 310, canvas.width - 100, 38);
    ctx.fillStyle = '#1C1C1C'; ctx.font = 'bold 15px Arial'; ctx.textAlign = 'right';
    ctx.fillText('תיאור השירות', canvas.width - 70, 334);
    ctx.textAlign = 'center';
    ctx.fillText('סכום', 200, 334);

    // Table row
    ctx.font = '15px Arial'; ctx.textAlign = 'right';
    ctx.fillText(rec.description || '', canvas.width - 70, 374);
    ctx.textAlign = 'center';
    ctx.fillText('₪' + Number(rec.total).toLocaleString('he-IL'), 200, 374);

    // Divider
    ctx.strokeStyle = '#ECE4DB'; ctx.lineWidth = 1;
    ctx.beginPath(); ctx.moveTo(50, 395); ctx.lineTo(canvas.width - 50, 395); ctx.stroke();

    // Totals
    const totY = 430;
    ctx.font = '15px Arial'; ctx.fillStyle = '#6B6B6B'; ctx.textAlign = 'right';
    ctx.fillText('סכום לפני מע"מ:', canvas.width - 50, totY);
    ctx.fillText(`מע"מ (${rec.vatPercent}%):`, canvas.width - 50, totY + 30);
    ctx.fillStyle = '#1C1C1C'; ctx.font = 'bold 17px Arial';
    ctx.fillText('סה"כ לתשלום:', canvas.width - 50, totY + 68);

    ctx.textAlign = 'left';
    ctx.font = '15px Arial'; ctx.fillStyle = '#6B6B6B';
    ctx.fillText('₪' + Number(rec.amount).toLocaleString('he-IL'), 100, totY);
    ctx.fillText('₪' + Number(rec.vat).toLocaleString('he-IL'), 100, totY + 30);
    ctx.fillStyle = '#C8102E'; ctx.font = 'bold 18px Arial';
    ctx.fillText('₪' + Number(rec.total).toLocaleString('he-IL'), 100, totY + 68);

    // Footer
    ctx.fillStyle = '#C8102E'; ctx.fillRect(20, canvas.height - 70, canvas.width - 40, 50);
    ctx.fillStyle = '#FFFFFF'; ctx.font = '14px Arial'; ctx.textAlign = 'center';
    ctx.fillText('תודה על הבחירה! ' + (rec.businessName || inv.businessName || ''), canvas.width / 2, canvas.height - 40);

    return canvas.toDataURL('image/png');
  };

  // תצוגה מקדימה של הטופס הנוכחי (ללא שמירה)
  const generateInvoice = () => { const url = drawInvoice(buildRecord()); setPreview(url); return url; };
  // תצוגה מקדימה של רשומה מהארכיון
  const previewRecord = (rec) => setPreview(drawInvoice(rec));

  // הורדת תמונת PNG של רשומה למחשב (לפי דרישה — לא חובה)
  const downloadRecord = (rec) => {
    const url = drawInvoice(rec);
    if (!url) return;
    const a = document.createElement('a');
    a.href = url; a.download = `חשבונית-${rec.num}.png`;
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
  };

  // מוריד קובץ PNG למחשב המקומי
  const _downloadPng = (pngDataUrl, num) => {
    if (!pngDataUrl) return;
    const a = document.createElement('a');
    a.href = pngDataUrl;
    a.download = `חשבונית-${num}.png`;
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
  };

  // פותח Gmail עם חשבון העסק (milim.lanetzah@gmail.com)
  const _bizGmailTo = (to, subject, body) => {
    const biz = (window.MLN && window.MLN.EMAIL) || 'milim.lanetzah@gmail.com';
    let url = `https://mail.google.com/mail/u/${encodeURIComponent(biz)}/?view=cm&fs=1&to=${encodeURIComponent(to || '')}`;
    if (subject) url += '&su=' + encodeURIComponent(subject);
    if (body)    url += '&body=' + encodeURIComponent(body);
    return url;
  };

  // חלופה — פותח Gmail עם פרטים כטקסט כשאין EmailJS
  const _openGmailFallback = (list, subject, rec) => {
    const body =
      `שלום,\n\nלהלן פרטי חשבונית מס מספר ${rec.num}.\n` +
      `(קובץ ה‑PNG הורד אוטומטית — ניתן לצרפו ידנית למייל)\n\n` +
      `לקוח: ${rec.customerName || ''}\n` +
      `תיאור: ${rec.description || ''}\n` +
      `סכום לפני מע"מ: ₪${Number(rec.amount).toLocaleString('he-IL')}\n` +
      `מע"מ (${rec.vatPercent}%): ₪${Number(rec.vat).toLocaleString('he-IL')}\n` +
      `סה"כ לתשלום: ₪${Number(rec.total).toLocaleString('he-IL')}\n\n` +
      `${rec.businessName || inv.businessName || ''}`;
    window.open(_bizGmailTo(list.join(','), subject, body), '_blank');
  };

  // שולח את החשבונית במייל עם תמונת ה‑PNG מצורפת.
  // אם EmailJS מוגדר עם תבנית "invoice" — שולח דרכו עם התמונה inline בגוף המייל.
  // אחרת — מוריד PNG ופותח Gmail עם הפרטים כטקסט.
  const sendInvoiceByEmail = async (rec, pngDataUrl) => {
    const list = String(rec.recipients || recipients || '').split(/[,;\s]+/).map(s => s.trim()).filter(Boolean);
    if (list.length === 0) { alert('יש להזין לפחות כתובת מייל אחת לשליחה.'); return; }
    const subject = `חשבונית מס #${rec.num} — ${rec.businessName || inv.businessName || ''}`;

    const ejs = window.MLN_EMAILJS;
    const hasEmailJS = !!(window.emailjs && ejs && ejs.publicKey && ejs.publicKey !== 'YOUR_EMAILJS_PUBLIC_KEY' && ejs.templateInvoice);

    if (hasEmailJS) {
      // שולח דרך EmailJS — התמונה מוטמעת כ‑data URL ב‑{{invoice_image}} בתבנית
      const templateParams = {
        to_email:      list[0],
        subject:       subject,
        invoice_num:   String(rec.num),
        customer_name: rec.customerName  || '',
        description:   rec.description   || '',
        amount:        '₪' + Number(rec.amount).toLocaleString('he-IL'),
        vat_percent:   String(rec.vatPercent),
        vat:           '₪' + Number(rec.vat).toLocaleString('he-IL'),
        total:         '₪' + Number(rec.total).toLocaleString('he-IL'),
        business_name: rec.businessName  || inv.businessName || '',
        invoice_image: pngDataUrl,
      };
      setSendStatus('sending');
      try {
        await window.emailjs.send(ejs.serviceId, ejs.templateInvoice, templateParams);
        setSendStatus('ok');
        _downloadPng(pngDataUrl, rec.num);
      } catch (err) {
        console.warn('[Invoice EmailJS] שגיאה:', err);
        setSendStatus('err');
        _downloadPng(pngDataUrl, rec.num);
        _openGmailFallback(list, subject, rec);
      }
    } else {
      // EmailJS לא מוגדר — מוריד PNG ופותח Gmail
      _downloadPng(pngDataUrl, rec.num);
      _openGmailFallback(list, subject, rec);
    }
  };

  // כפתור "שלח" ברשומת ארכיון — מוריד PNG ופותח Gmail עם תבנית מוכנה
  const openGmail = (rec) => {
    const pngDataUrl = drawInvoice(rec);
    _downloadPng(pngDataUrl, rec.num);
    const to = rec.clientEmail || rec.recipients || '';
    const subject = `חשבונית ${rec.num} — מילים לנצח`;
    const body =
      `שלום ${rec.clientName || rec.customerName || ''},\n\n` +
      `מצורפת חשבונית מספר ${rec.num} עבור ${rec.description || ''}.\n` +
      `סכום לתשלום: ₪${Number(rec.total).toLocaleString('he-IL')}\n\n` +
      `בברכה,\nמילים לנצח`;
    window.open(_bizGmailTo(to, subject, body), '_blank');
  };

  const guardOk = () => {
    if (!String(form.customerName).trim() && amountNum <= 0) { alert('יש למלא לפחות שם לקוח או סכום לפני שמירה/שליחה.'); return false; }
    return true;
  };
  const resetForm = () => { setForm({ customerName: '', description: '', amount: '', date: new Date().toISOString().slice(0, 10) }); setPreview(null); };

  // שומר את החשבונית בארכיון באתר + מקדם את המונה.
  // אם sendToo — מוריד PNG ופותח Gmail עם תבנית מוכנה (ללא EmailJS).
  const finalize = (sendToo) => {
    if (!guardOk()) return;
    const rec = buildRecord();
    const pngDataUrl = drawInvoice(rec);
    setPreview(pngDataUrl);
    if (sendToo) {
      const to = String(rec.clientEmail || recipients || '').split(/[,;\s]+/).map(s => s.trim()).filter(Boolean)[0] || '';
      _downloadPng(pngDataUrl, rec.num);
      const subject = `חשבונית ${rec.num} — מילים לנצח`;
      const body =
        `שלום ${rec.clientName || rec.customerName || ''},\n\n` +
        `מצורפת חשבונית מספר ${rec.num} עבור ${rec.description || ''}.\n` +
        `סכום לתשלום: ₪${Number(rec.total).toLocaleString('he-IL')}\n\n` +
          `בברכה,\nמילים לנצח`;
      window.open(_bizGmailTo(to, subject, body), '_blank');
    }
    onChange({
      ...data,
      invoices: [rec, ...archive],
      invoice: { ...inv, nextInvoiceNum: rec.num + 1, defaultRecipients: recipients },
    });
    if (window.MLN_INVOICES) {
      window.MLN_INVOICES.save(rec);
      setRemoteInvoices(prev => prev !== null ? [rec, ...(prev || [])] : null);
    }
    resetForm();
  };

  const delFromArchive = (id) => {
    if (!confirm('למחוק חשבונית מהארכיון? פעולה זו אינה מוחקת מיילים שכבר נשלחו.')) return;
    onChange({ ...data, invoices: archive.filter(r => r.id !== id) });
    if (remoteInvoices !== null) setRemoteInvoices(prev => (prev || []).filter(r => r.id !== id));
  };
  const fmtInvDate = (iso) => { try { return new Date(iso).toLocaleDateString('he-IL', { day: '2-digit', month: '2-digit', year: 'numeric' }); } catch (e) { return iso; } };

  return (
    <div style={{ maxWidth: 780 }}>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }} className="mln-adm-prod">
      {/* Settings */}
      <div>
        <p style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: 'var(--ink-900)', margin: '0 0 14px' }}>פרטי העסק (נשמרים)</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div><span style={admLabel}>שם העסק</span><input value={inv.businessName} onChange={e => updInv({ businessName: e.target.value })} style={admInput} /></div>
          <div><span style={admLabel}>כתובת</span><input value={inv.businessAddress} onChange={e => updInv({ businessAddress: e.target.value })} style={admInput} /></div>
          <div><span style={admLabel}>ח.פ / ע.מ</span><input value={inv.businessId} onChange={e => updInv({ businessId: e.target.value })} style={admInput} /></div>
          <div><span style={admLabel}>מספר עוסק מורשה</span><input value={inv.vatNumber} onChange={e => updInv({ vatNumber: e.target.value })} style={admInput} /></div>
          <div><span style={admLabel}>אחוז מע"מ (%)</span><input type="number" min="0" max="100" value={inv.vatPercent} onChange={e => updInv({ vatPercent: Number(e.target.value) })} style={admInput} /></div>
        </div>

        <p style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: 'var(--ink-900)', margin: '22px 0 14px' }}>פרטי החשבונית הנוכחית</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div><span style={admLabel}>שם הלקוח</span><input value={form.customerName} onChange={e => setForm(f => ({ ...f, customerName: e.target.value }))} style={admInput} /></div>
          <div><span style={admLabel}>תיאור השירות</span><textarea value={form.description} rows={2} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} style={{ ...admInput, resize: 'vertical' }} /></div>
          <div><span style={admLabel}>מחיר סופי (כולל מע"מ) (₪)</span><input type="number" min="0" value={form.amount} onChange={e => setForm(f => ({ ...f, amount: e.target.value }))} style={admInput} /></div>
          <div><span style={admLabel}>תאריך</span><input type="date" value={form.date} onChange={e => setForm(f => ({ ...f, date: e.target.value }))} style={admInput} /></div>
          {total > 0 && (
            <div style={{ background: 'var(--cream)', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', padding: '12px 14px', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-700)' }}>
              לפני מע"מ: ₪{amountNum.toLocaleString('he-IL')}<br />
              מע"מ ({inv.vatPercent}%): ₪{vatAmount.toLocaleString('he-IL')}<br />
              <strong style={{ color: 'var(--brand)' }}>סה"כ לתשלום: ₪{total.toLocaleString('he-IL')}</strong>
            </div>
          )}
        </div>

        {/* Recipients */}
        <div style={{ marginTop: 16 }}>
          <span style={admLabel}>שליחה אל (כתובות מייל, מופרדות בפסיק)</span>
          <input value={recipients} onChange={e => setRecipients(e.target.value)}
            placeholder="name1@gmail.com, name2@gmail.com" style={admInput} />
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap' }}>
          <button onClick={generateInvoice} style={admGhost}><Icon name="eye" size={17} /> תצוגה מקדימה</button>
          <button onClick={() => finalize(false)} style={{ ...admBtn, background: 'var(--brand)', color: '#fff' }}><Icon name="check" size={17} /> שמור באתר</button>
          <button onClick={() => finalize(true)} style={{ ...admBtn, background: 'var(--brand)', color: '#fff' }}>
            <Icon name="mail" size={17} /> שלח במייל + הורד PNG
          </button>
          <button onClick={() => { if (guardOk()) downloadRecord(buildRecord()); }} style={admGhost}><Icon name="upload" size={17} /> הורד PNG</button>
        </div>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--ink-400)', margin: '10px 0 0', lineHeight: 1.6 }}>
          "שמור באתר" שומר בארכיון בלבד. "שלח במייל + הורד PNG" מצייר את החשבונית, מוריד קובץ PNG למחשב, ופותח Gmail עם הנוסח המוכן — צרפי את הקובץ שהורד לפני השליחה.
        </p>
      </div>

      {/* Preview */}
      <div>
        <canvas ref={canvasRef} style={{ display: 'none' }} />
        {preview ? (
          <div>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-500)', marginBottom: 8 }}>תצוגה מקדימה</p>
            <img src={preview} alt="חשבונית" style={{ width: '100%', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-md)' }} />
            <a href={preview} download={`invoice-${inv.nextInvoiceNum}.png`} style={{ ...admGhost, marginTop: 10, textDecoration: 'none', display: 'inline-flex' }}><Icon name="upload" size={16} /> הורד תמונה</a>
          </div>
        ) : (
          <div style={{ border: '1.5px dashed var(--border)', borderRadius: 'var(--radius-lg)', height: 400, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-300)', fontFamily: 'var(--font-body)' }}>
            תצוגה מקדימה תופיע כאן
          </div>
        )}
      </div>
    </div>

      {/* ארכיון חשבוניות — נשמר באתר לפי תאריך */}
      {archive.length > 0 && (
        <div style={{ marginTop: 30 }}>
          <p style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: 'var(--ink-900)', margin: '0 0 12px' }}>ארכיון חשבוניות ({archive.length})</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[...archive].sort((a, b) => new Date(b.date) - new Date(a.date)).map(rec => (
              <div key={rec.id} style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '13px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
                <div>
                  <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--ink-900)' }}>#{rec.num} · {rec.customerName || '(ללא שם)'}</span>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--ink-400)', marginTop: 3 }}>{fmtInvDate(rec.date)} · סה"כ ₪{Number(rec.total).toLocaleString('he-IL')}</div>
                </div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  <button onClick={() => previewRecord(rec)} style={{ ...admGhost, fontSize: 13, padding: '7px 11px' }}><Icon name="eye" size={14} /> תצוגה</button>
                  <button onClick={() => downloadRecord(rec)} style={{ ...admGhost, fontSize: 13, padding: '7px 11px' }}><Icon name="upload" size={14} /> הורד</button>
                  <button onClick={() => openGmail(rec)} style={{ ...admGhost, fontSize: 13, padding: '7px 11px' }}><Icon name="mail" size={14} /> שלח</button>
                  <button onClick={() => delFromArchive(rec.id)} title="מחק מהארכיון" style={admDanger} onMouseEnter={e => e.currentTarget.style.color = 'var(--brand)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-300)'}><Icon name="trash" size={16} /></button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// ---------- Permissions — ניהול מיילים מורשים ----------
const PermissionsAdmin = ({ data, onChange }) => {
  const [me, setMe] = useStateAdm('');
  const [newMail, setNewMail] = useStateAdm('');
  const [mailErr, setMailErr] = useStateAdm('');

  useEffectAdm(() => {
    let active = true;
    if (window.MLN_AUTH) {
      window.MLN_AUTH.getUser().then(u => { if (active) setMe(u ? u.email : ''); }).catch(() => {});
    }
    return () => { active = false; };
  }, []);

  const admins = data.admins || [];

  const addMail = (e) => {
    e.preventDefault();
    const m = newMail.trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)) { setMailErr('כתובת מייל לא תקינה'); return; }
    if (admins.map(a => a.toLowerCase()).includes(m)) { setMailErr('מייל זה כבר ברשימה'); return; }
    onChange({ ...data, admins: [...admins, m] });
    setNewMail(''); setMailErr('');
  };

  const removeMail = (mail) => {
    if (mail.toLowerCase() === me.toLowerCase()) return;
    onChange({ ...data, admins: admins.filter(a => a.toLowerCase() !== mail.toLowerCase()) });
  };

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  return (
    <div style={{ maxWidth: 640 }}>

      {/* סטטוס מחובר */}
      {me && (
        <div style={{ background: 'var(--surface-tint)', border: '1px solid var(--red-200)', borderRadius: 'var(--radius-lg)', padding: '14px 16px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ color: 'var(--brand)', display: 'inline-flex' }}><Icon name="lock" size={18} /></span>
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink-900)' }}>מחובר/ת כעת: <strong dir="ltr">{me}</strong></span>
        </div>
      )}

      {/* אבטחה — מידע */}
      <div style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '16px 20px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ color: '#1d8a4e', display: 'inline-flex', flexShrink: 0 }}><Icon name="lock" size={20} /></span>
        <div>
          <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14.5, color: 'var(--ink-900)', marginBottom: 3 }}>כניסה מאובטחת</div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--ink-500)', lineHeight: 1.5 }}>כניסה אפשרית רק למיילים ברשימה למטה.</div>
        </div>
      </div>

      {/* רשימת מיילים מורשים */}
      <div style={{ marginBottom: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ ...admLabel, marginBottom: 0, fontSize: 14 }}>מיילים מורשים לאזור הניהול</span>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--ink-400)' }}>{admins.length} כתובות</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
        {admins.map(mail => {
          const isMe = mail.toLowerCase() === me.toLowerCase();
          return (
            <div key={mail} style={{ background: 'var(--white)', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', padding: '10px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-900)', direction: 'ltr' }}>
                <span style={{ color: 'var(--brand)', display: 'inline-flex' }}><Icon name="mail" size={15} /></span>
                {mail}
                {isMe && <span style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, background: 'var(--surface-tint)', color: 'var(--brand)', borderRadius: 6, padding: '2px 7px', marginRight: 4 }}>אני</span>}
              </div>
              {!isMe && (
                <button onClick={() => removeMail(mail)} title="הסר מייל" style={admDanger} onMouseEnter={e => e.currentTarget.style.color = 'var(--brand)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-300)'}>
                  <Icon name="x" size={16} />
                </button>
              )}
            </div>
          );
        })}
        {admins.length === 0 && (
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-400)', textAlign: 'center', padding: '16px 0' }}>אין מיילים ברשימה</div>
        )}
      </div>

      {/* הוספת מייל */}
      <form onSubmit={addMail} style={{ display: 'flex', gap: 8, alignItems: 'flex-start', flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 220 }}>
          <input
            type="email" value={newMail} dir="ltr"
            onChange={e => { setNewMail(e.target.value); setMailErr(''); }}
            placeholder="הוסיפי כתובת מייל חדשה"
            style={{ ...admInput, borderColor: mailErr ? 'var(--brand)' : 'var(--border)' }}
          />
          {mailErr && <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--brand)', display: 'block', marginTop: 4 }}>{mailErr}</span>}
        </div>
        <button type="submit" disabled={!emailRegex.test(newMail.trim())} style={{ ...admBtn, background: 'var(--brand)', color: '#fff', opacity: emailRegex.test(newMail.trim()) ? 1 : 0.5 }}>
          <Icon name="plus" size={16} /> הוסיפי
        </button>
      </form>

      <div style={{ background: 'var(--cream)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '14px 18px', fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.75, color: 'var(--ink-600)', marginTop: 24 }}>
        <strong style={{ color: 'var(--ink-900)' }}>הוספת מנהל/ת חדש/ה:</strong> הוסיפי את המייל כאן ↑, ואז צרי חשבון Supabase עבורו/ה דרך לוח הבקרה (Authentication → Add user). בכניסה יתבקשו להזין מייל, סיסמה, וקוד שיישלח למייל שלהם.
      </div>
    </div>
  );
};

const chip = (active) => ({ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13.5, cursor: 'pointer', padding: '8px 15px', borderRadius: 'var(--radius-pill)', border: '1.5px solid ' + (active ? 'var(--brand)' : 'var(--border)'), background: active ? 'var(--brand)' : 'var(--white)', color: active ? '#fff' : 'var(--ink-700)', transition: 'all 200ms' });

const TABS = [
  { id: 'inbox',        label: 'תיבת פניות', icon: 'inbox'  },
  { id: 'store',        label: 'חנות',        icon: 'cart'   },
  { id: 'gallery',      label: 'גלריה',       icon: 'image'  },
  { id: 'testimonials', label: 'המלצות',      icon: 'quote'  },
  { id: 'poem',         label: 'שיר',         icon: 'music'  },
  { id: 'about',        label: 'אודות',       icon: 'edit'   },
  { id: 'invoice',      label: 'חשבונית',     icon: 'frame'  },
  { id: 'permissions',  label: 'הרשאות',      icon: 'lock'   },
];

const AdminPanel = ({ open, onClose, data, onChange }) => {
  const [authed, setAuthed] = useStateAdm(() => sessionStorage.getItem('mln_admin') === '1');
  const [tab, setTab] = useStateAdm('inbox');
  const [inboxItems, setInboxItems] = useStateAdm([]);
  const [inboxLoading, setInboxLoading] = useStateAdm(false);
  const [inboxError, setInboxError] = useStateAdm(null);

  useEffectAdm(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const refreshInbox = async () => {
    if (!window.MLN_AUTH) return;
    setInboxLoading(true); setInboxError(null);
    const { items, error } = await window.MLN_AUTH.fetchInbox();
    setInboxItems(items || []);
    setInboxError(error || null);
    setInboxLoading(false);
  };

  useEffectAdm(() => {
    if (open && authed) refreshInbox();
  }, [open, authed]);

  useEffectAdm(() => {
    if (!open || !authed) return;
    if (!window.MLN_AUTH) return;
    window.MLN_AUTH.getUser().then(user => {
      if (!user) {
        sessionStorage.removeItem('mln_admin');
        setAuthed(false);
      }
    });
  }, [open]);

  if (!open) return null;
  const auth = () => { sessionStorage.setItem('mln_admin', '1'); setAuthed(true); };
  const logout = () => { sessionStorage.removeItem('mln_admin'); setAuthed(false); onClose(); };
  const unread = inboxItems.filter(m => !m.read).length;

  if (!authed) {
    return <div style={overlay}><AdminLogin data={data} onAuth={auth} onClose={onClose} /></div>;
  }

  return (
    <div style={{ ...overlay, alignItems: 'stretch', justifyContent: 'stretch', padding: 0 }}>
      <div style={{ background: 'var(--bg-alt)', width: '100%', height: '100%', display: 'flex', flexDirection: 'column', animation: 'mlnFade 240ms var(--ease-out)' }}>
        <div style={{ background: 'var(--red-900)', color: '#FFF6F2', padding: '0 clamp(16px,3vw,32px)', flexShrink: 0 }}>
          <div style={{ maxWidth: 1100, margin: '0 auto', height: 66, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
              <Icon name="gear" size={20} style={{ flexShrink: 0 }} />
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(14px, 3.5vw, 19px)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>אזור ניהול · מילים לנצח</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
              <button onClick={logout} style={{ ...admBtn, background: 'rgba(255,246,242,0.1)', color: '#FFF6F2', border: '1px solid rgba(255,246,242,0.22)', fontSize: 'clamp(12px,3vw,14.5px)', padding: 'clamp(6px,1.5vw,10px) clamp(10px,2vw,18px)', minHeight: 44, minWidth: 44 }}><Icon name="logout" size={16} /> <span className="mln-adm-logout-label">יציאה</span></button>
              <button onClick={onClose} aria-label="סגירה" style={{ width: 44, height: 44, borderRadius: '50%', border: '1px solid rgba(255,246,242,0.22)', background: 'rgba(255,246,242,0.1)', color: '#FFF6F2', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="x" size={20} /></button>
            </div>
          </div>
        </div>
        <div className="mln-adm-tabs" style={{ background: 'var(--white)', borderBottom: '1px solid var(--border)', flexShrink: 0, overflowX: 'auto', WebkitOverflowScrolling: 'touch' }}>
          <div style={{ maxWidth: 1100, margin: '0 auto', padding: '0 clamp(8px,2vw,32px)', display: 'flex', gap: 2 }}>
            {TABS.map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} title={t.label} style={{
                position: 'relative', background: 'none', border: 'none', cursor: 'pointer',
                padding: 'clamp(10px,2vw,18px) clamp(8px,1.5vw,14px) clamp(8px,1.5vw,15px)',
                minHeight: 44, minWidth: 44,
                fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap',
                color: tab === t.id ? 'var(--brand)' : 'var(--ink-500)',
                borderBottom: '3px solid ' + (tab === t.id ? 'var(--brand)' : 'transparent'),
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                <Icon name={t.icon} size={16} />
                <span style={{ display: 'inline' }}>{t.label}</span>
                {t.id === 'inbox' && unread > 0 && <span style={{ background: 'var(--brand)', color: '#fff', fontSize: 11, fontWeight: 700, minWidth: 18, height: 18, borderRadius: 9, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: '0 5px' }}>{unread}</span>}
              </button>
            ))}
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          <div style={{ maxWidth: 1100, margin: '0 auto', padding: 'clamp(20px,3vw,32px)' }}>
            {tab === 'inbox'        && <InboxAdmin        items={inboxItems} loading={inboxLoading} error={inboxError} onRefresh={refreshInbox} />}
            {tab === 'store'        && <StoreAdmin        data={data} onChange={onChange} />}
            {tab === 'gallery'      && <GalleryAdmin      data={data} onChange={onChange} />}
            {tab === 'testimonials' && <TestimonialsAdmin data={data} onChange={onChange} />}
            {tab === 'poem'         && <PoemAdmin         data={data} onChange={onChange} />}
            {tab === 'about'        && <AboutAdmin        data={data} onChange={onChange} />}
            {tab === 'invoice'      && <InvoiceAdmin      data={data} onChange={onChange} />}
            {tab === 'permissions'  && <PermissionsAdmin  data={data} onChange={onChange} />}
          </div>
        </div>
      </div>
    </div>
  );
};

const overlay = { position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(36,8,14,0.55)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 };
window.AdminPanel = AdminPanel;
