// resource-shelf.jsx — رفوف موارد قابلة للتحديث: المالك يرفع مرفقاً (قاموس، كتاب، دليل) ويظهر للجميع
// stored in store.data.shelves[bucket] — persisted with the rest of the platform content

function ResourceShelf({ t, L, store, auth, bucket, eyebrow, title, sub, kindLabel, accent = 'mint' }) {
  const toast = useToast();
  const data = store.data;
  const isOwner = !!(auth && auth.user);
  const items = ((data.shelves || {})[bucket]) || [];
  const [open, setOpen] = React.useState(false);
  const [f, setF] = React.useState({ title: '', author: '', note: '', link: '', files: [] });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const write = (list) => {
    const next = structuredClone(data);
    next.shelves = { ...(next.shelves || {}) };
    next.shelves[bucket] = list;
    store.save(next);
  };
  const add = (e) => {
    e.preventDefault();
    if (!f.title.trim()) return;
    write([{ id: 'r' + Date.now().toString(36), ...f, at: new Date().toISOString(), by: auth && auth.user ? L(auth.user.name) : '' }, ...items]);
    setF({ title: '', author: '', note: '', link: '', files: [] });
    setOpen(false);
    toast(t('shelf_saved'));
  };
  const del = (id) => { if (confirm(t('shelf_del_q'))) write(items.filter(x => x.id !== id)); };

  if (!isOwner && !items.length) return null;

  return (
    <div style={{ marginTop: 56 }} id={'shelf-' + bucket}>
      <Reveal><Head eyebrow={eyebrow} title={title} sub={sub} icon="layers" /></Reveal>

      {isOwner && (
        <div style={{ marginTop: 22 }}>
          {!open ? (
            <button className="btn btn-primary" onClick={() => setOpen(true)}><Icon.plus s={16} /> {kindLabel || t('shelf_add')}</button>
          ) : (
            <form className="card card-pad" style={{ display: 'grid', gap: 16, padding: 26 }} onSubmit={add}>
              <div className="eyebrow" style={{ color: `var(--${accent})` }}><Icon.plus s={14} /> {kindLabel || t('shelf_add')}</div>
              <div className="grid g2" style={{ gap: 16 }}>
                <Field label={t('shelf_f_title')} required><input className="input" required value={f.title} onChange={e => set('title', e.target.value)} placeholder="—" /></Field>
                <Field label={t('shelf_f_author')}><input className="input" value={f.author} onChange={e => set('author', e.target.value)} placeholder="—" /></Field>
              </div>
              <Field label={t('shelf_f_note')}><textarea className="textarea" style={{ minHeight: 80 }} value={f.note} onChange={e => set('note', e.target.value)} placeholder="—" /></Field>
              <Field label={t('shelf_f_link')}><input className="input" dir="ltr" value={f.link} onChange={e => set('link', e.target.value)} placeholder="https://" /></Field>
              <AttachField t={t} L={L} label={t('attachments')} hint={t('shelf_hint')} value={f.files} onChange={v => set('files', v)} />
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                <button className="btn btn-primary"><Icon.check s={16} /> {t('save')}</button>
                <button type="button" className="btn btn-ghost" onClick={() => setOpen(false)}>{t('cancel')}</button>
              </div>
            </form>
          )}
        </div>
      )}

      {items.length === 0 ? (
        isOwner ? <p className="muted" style={{ fontSize: 13.5, marginTop: 16 }}>{t('shelf_empty')}</p> : null
      ) : (
        <div className="grid g2" style={{ marginTop: 24 }}>
          {items.map((r, i) => (
            <Reveal key={r.id} delay={(i % 2) * 60}>
              <div className="card card-pad" style={{ height: '100%', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                <span style={{ flex: 'none', width: 44, height: 58, borderRadius: 6, background: `linear-gradient(140deg, color-mix(in srgb, var(--${accent}) 34%, transparent), color-mix(in srgb, var(--${accent}) 10%, transparent))`, border: `1px solid color-mix(in srgb, var(--${accent}) 40%, transparent)`, display: 'grid', placeItems: 'center', color: `var(--${accent})` }}><Icon.book s={19} /></span>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <b style={{ fontSize: 15.5, display: 'block', lineHeight: 1.45 }}>{r.title}</b>
                  {r.author && <div style={{ fontSize: 13, marginTop: 5, color: 'var(--accent)', fontWeight: 600 }}>{r.author}</div>}
                  {r.note && <p className="muted" style={{ fontSize: 13.5, marginTop: 8, lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>{r.note}</p>}
                  {(r.files || []).length > 0 && <div style={{ marginTop: 12 }}><AttachList items={r.files} L={L} /></div>}
                  <div style={{ display: 'flex', gap: 10, marginTop: 12, flexWrap: 'wrap', alignItems: 'center' }}>
                    {r.link && <a className="btn btn-ghost btn-sm" href={r.link} target="_blank" rel="noopener"><Icon.globe s={14} /> {t('visit')}</a>}
                    {isOwner && <button className="btn btn-dark btn-sm" onClick={() => del(r.id)}><Icon.x s={14} /> {t('delete')}</button>}
                  </div>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      )}
    </div>
  );
}

window.ResourceShelf = ResourceShelf;
