// ondemand.jsx — "المنصة المستمرة": 24/7 library of recorded courses, videos and downloadable files

function embedUrl(url) {
  const u = String(url || '').trim();
  if (!u) return null;
  let m = u.match(/(?:youtube\.com\/(?:watch\?v=|live\/|embed\/)|youtu\.be\/)([\w-]{6,})/i);
  if (m) return 'https://www.youtube.com/embed/' + m[1];
  m = u.match(/vimeo\.com\/(\d+)/i);
  if (m) return 'https://player.vimeo.com/video/' + m[1];
  m = u.match(/drive\.google\.com\/file\/d\/([\w-]+)/i);
  if (m) return 'https://drive.google.com/file/d/' + m[1] + '/preview';
  if (/\.(mp4|webm|ogg|m4v)(\?|$)/i.test(u)) return u;
  return null;
}
const isDirectVideo = (u) => /\.(mp4|webm|ogg|m4v)(\?|$)/i.test(String(u || ''));

function libraryItems(data) {
  return (data.courses || [])
    .filter(c => (c.term || 'upcoming') === 'past' || c.video || (c.links || []).length || (c.files || []).length)
    .map(c => ({ c, assets: ((c.files || []).length + (c.links || []).length + (c.video ? 1 : 0)) }))
    .sort((a, b) => b.assets - a.assets);
}

/* ---- link rows editor (used inside CourseForm) ---- */
function LinksField({ label, hint, value = [], onChange, L }) {
  const rows = value || [];
  const upd = (i, k, v) => onChange(rows.map((r, j) => j === i ? { ...r, [k]: v } : r));
  return (
    <div className="field">
      <label>{label} <span className="help" style={{ fontWeight: 400 }}>({L({ ar: 'اختياري', en: 'optional' })})</span></label>
      <div style={{ display: 'grid', gap: 10 }}>
        {rows.map((r, i) => (
          <div key={r.id || i} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <input className="input" style={{ flex: '0 0 34%' }} value={r.title || ''} onChange={e => upd(i, 'title', e.target.value)} placeholder={L({ ar: 'اسم الملف', en: 'File name' })} />
            <input className="input" style={{ flex: 1 }} value={r.url || ''} onChange={e => upd(i, 'url', e.target.value)} placeholder="https://" dir="ltr" />
            <button type="button" className="btn btn-dark btn-sm" style={{ padding: 8 }} onClick={() => onChange(rows.filter((_, j) => j !== i))}><Icon.x s={14} /></button>
          </div>
        ))}
      </div>
      <button type="button" className="btn btn-ghost btn-sm" style={{ marginTop: 10, justifySelf: 'start' }} onClick={() => onChange([...rows, { id: 'l' + Date.now(), title: '', url: '' }])}><Icon.plus s={15} /> {L({ ar: 'إضافة رابط', en: 'Add link' })}</button>
      {hint && <span className="help">{hint}</span>}
    </div>
  );
}

/* ---- quick "add material" form: a link is all it takes ---- */
function MaterialForm({ t, L, item, onSave, onCancel, onDelete }) {
  const [c, setC] = React.useState(item);
  const upd = (k, v) => setC(s => ({ ...s, [k]: v }));
  const updL = (k, v) => setC(s => ({ ...s, [k]: { ...(typeof s[k] === 'object' && s[k] ? s[k] : {}), ar: v, en: (s[k] && s[k].en) || v } }));
  const valid = L(c.title).trim() && (String(c.video || '').trim() || (c.links || []).some(l => l.url) || (c.files || []).length);
  return (
    <div className="card-pad" style={{ padding: 28 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div>
          <div className="eyebrow"><Icon.play s={14} /> {t('lib_eyebrow')}</div>
          <h3 style={{ fontSize: 21, marginTop: 6 }}>{L(item.title).trim() ? t('mat_edit') : t('mat_new')}</h3>
        </div>
        <button className="btn btn-dark btn-sm" onClick={onCancel} style={{ padding: 8 }}><Icon.x s={16} /></button>
      </div>
      <div className="conf-note" style={{ marginTop: 16 }}><Icon.spark s={16} /> {t('mat_hint')}</div>
      <div style={{ display: 'grid', gap: 16, marginTop: 18 }}>
        <Field label={t('mat_title')} required><input className="input" value={L(c.title)} onChange={e => updL('title', e.target.value)} placeholder={L({ ar: 'مثال: محاضرة التفكير التصميمي في الرعاية الأولية', en: 'e.g. Design thinking in primary care' })} /></Field>
        <Field label={t('course_video')} hint={t('course_video_hint')}>
          <input className="input" value={c.video || ''} onChange={e => upd('video', e.target.value)} placeholder="https://youtu.be/…" dir="ltr" style={{ textAlign: 'start' }} />
        </Field>
        <LinksField L={L} label={t('course_links')} hint={t('course_links_hint')} value={c.links || []} onChange={v => upd('links', v)} />
        <div className="grid g2" style={{ gap: 16 }}>
          <Field label={t('mat_source')}><input className="input" value={L(c.presenter)} onChange={e => updL('presenter', e.target.value)} placeholder="—" /></Field>
          <Field label={t('mat_date')}><input className="input" value={L(c.date)} onChange={e => updL('date', e.target.value)} placeholder={L({ ar: '٥ أغسطس ٢٠٢٦', en: '5 August 2026' })} /></Field>
        </div>
        <Field label={t('mat_desc')}><textarea className="textarea" value={L(c.objective)} onChange={e => updL('objective', e.target.value)} placeholder="—" /></Field>
        <div className="grid g2" style={{ gap: 16 }}>
          <Field label={L({ ar: 'التصنيف', en: 'Category' })}>
            <select className="select" value={c.cat} onChange={e => upd('cat', e.target.value)}>
              {COURSE_CATS.filter(x => x.id !== 'all').map(x => <option key={x.id} value={x.id}>{L(x.label)}</option>)}
            </select>
          </Field>
          <Field label={L({ ar: 'لون البطاقة', en: 'Accent' })}>
            <select className="select" value={c.accent} onChange={e => upd('accent', e.target.value)}>
              <option value="mint">Mint</option><option value="purple">Purple</option><option value="gold">Gold</option>
            </select>
          </Field>
        </div>
        <AttachField t={t} L={L} label={t('attachments')} hint={t('attach_hint')} value={c.files || []} onChange={v => upd('files', v)} />
      </div>
      <div style={{ display: 'flex', gap: 12, marginTop: 24, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
        {onDelete && <button className="btn btn-dark" style={{ color: 'var(--rose)', marginInlineEnd: 'auto' }} onClick={onDelete}><Icon.trash s={15} /> {t('mat_del')}</button>}
        <button className="btn btn-dark" onClick={onCancel}>{t('cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onSave(c)}><Icon.check s={16} /> {t('save')}</button>
      </div>
    </div>
  );
}

function blankMaterial() {
  const today = new Date().toLocaleDateString('ar-EG', { year: 'numeric', month: 'long', day: 'numeric' });
  return { id: 'm' + Date.now(), term: 'past', title: { ar: '', en: '' }, presenter: { ar: '', en: '' }, date: { ar: today, en: today }, objective: { ar: '', en: '' }, outcomes: '', target: '', dur: '', cat: 'innovation', mode: 'virtual', accent: 'mint', video: '', links: [], files: [] };
}

function LibraryCard({ item, t, L, onOpen, onEdit }) {
  const { c } = item;
  const hasVid = !!c.video;
  const nFiles = (c.files || []).length + (c.links || []).length;
  return (
    <div className="card hoverable" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', cursor: 'pointer' }} onClick={onOpen}>
      <div style={{ position: 'relative' }}>
        <PH h={132} label={null} icon={hasVid ? 'play' : 'layers'} style={{ borderRadius: 0, border: 0, borderBottom: '1px solid var(--line)' }} />
        {hasVid && (
          <span style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
            <span className="av" style={{ width: 52, height: 52, background: 'var(--accent)', boxShadow: '0 8px 24px rgba(0,0,0,.35)' }}><Icon.play s={22} /></span>
          </span>
        )}
        <span className="badge mint" style={{ position: 'absolute', insetInlineEnd: 12, top: 12, backdropFilter: 'blur(6px)' }}><Icon.clock s={12} /> 24/7</span>
        {onEdit && <button className="btn btn-dark btn-sm" style={{ position: 'absolute', insetInlineStart: 12, top: 12, padding: 8 }} onClick={(e) => { e.stopPropagation(); onEdit(); }}><Icon.pen s={14} /></button>}
      </div>
      <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <span className={"badge " + (c.accent || 'mint')}>{L(COURSE_CATS.find(x => x.id === c.cat)?.label)}</span>
          {hasVid && <span className="badge purple"><Icon.play s={12} /> {t('lib_recording')}</span>}
          {nFiles > 0 && <span className="chip" style={{ padding: '4px 10px', fontSize: 12 }}><Icon.layers s={12} /> {nFiles} {t('lib_files')}</span>}
        </div>
        <h3 style={{ fontSize: 17.5 }}>{L(c.title) || L({ ar: '(بدون اسم)', en: '(untitled)' })}</h3>
        {c.objective && <p className="muted clamp2" style={{ fontSize: 13.5, lineHeight: 1.6, margin: 0 }}>{L(c.objective)}</p>}
        <div className="muted" style={{ fontSize: 13, display: 'flex', gap: 14, flexWrap: 'wrap', marginTop: 'auto', paddingTop: 8 }}>
          {c.presenter && <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}><Icon.user s={14} /> {L(c.presenter)}</span>}
          {c.date && <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}><Icon.clock s={14} /> {L(c.date)}</span>}
        </div>
        <button className="btn btn-primary" style={{ marginTop: 4 }}>{hasVid ? <><Icon.play s={16} /> {t('lib_watch')}</> : <><Icon.arrow s={15} /> {t('view_details')}</>}</button>
      </div>
    </div>
  );
}

function LibraryViewer({ c, t, L, data, onClose }) {
  const emb = embedUrl(c.video);
  const me = window.savedMe ? window.savedMe() : {};
  const mine = (data.enrollments || []).find(r => r.courseId === c.id && r.attended && me.empId && String(r.empId).trim().toLowerCase() === String(me.empId).trim().toLowerCase());
  return (
    <div className="card-pad" style={{ padding: 26 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div>
          <div className="eyebrow"><Icon.play s={14} /> {t('lib_eyebrow')}</div>
          <h3 style={{ fontSize: 21, marginTop: 6 }}>{L(c.title)}</h3>
          <p className="muted" style={{ fontSize: 13.5, marginTop: 5 }}>{L(c.presenter)}{c.date ? ' · ' + L(c.date) : ''}{c.dur ? ' · ' + L(c.dur) : ''}</p>
        </div>
        <button className="btn btn-dark btn-sm" onClick={onClose} style={{ padding: 8 }}><Icon.x s={16} /></button>
      </div>

      {emb ? (
        <div style={{ marginTop: 18, borderRadius: 'var(--r)', overflow: 'hidden', border: '1px solid var(--line)', background: '#000', aspectRatio: '16/9' }}>
          {isDirectVideo(emb)
            ? <video src={emb} controls playsInline style={{ width: '100%', height: '100%', display: 'block' }} />
            : <iframe src={emb} title={L(c.title)} allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; fullscreen" allowFullScreen style={{ width: '100%', height: '100%', border: 0, display: 'block' }} />}
        </div>
      ) : c.video ? (
        <a className="btn btn-primary btn-lg" href={c.video} target="_blank" rel="noopener" style={{ marginTop: 18 }}><Icon.play s={18} /> {t('lib_open_ext')}</a>
      ) : null}

      {c.objective && <p className="muted" style={{ fontSize: 14.5, marginTop: 16, lineHeight: 1.7 }}>{L(c.objective)}</p>}
      {c.outcomes && (
        <div style={{ marginTop: 16 }}>
          <div className="eyebrow"><Icon.target s={14} /> {t('outcomes')}</div>
          <p style={{ fontSize: 14, marginTop: 8, lineHeight: 1.7 }}>{L(c.outcomes)}</p>
        </div>
      )}

      {(c.files || []).length > 0 && (
        <div style={{ marginTop: 18 }}>
          <div className="eyebrow"><Icon.layers s={14} /> {t('lib_downloads')} · {c.files.length}</div>
          <div style={{ marginTop: 10 }}><AttachList items={c.files} L={L} /></div>
        </div>
      )}
      {(c.links || []).filter(l => l.url).length > 0 && (
        <div style={{ marginTop: 18 }}>
          <div className="eyebrow"><Icon.globe s={14} /> {t('lib_links')}</div>
          <div className="attach-list" style={{ marginTop: 10 }}>
            {(c.links || []).filter(l => l.url).map((l, i) => (
              <a key={l.id || i} className="attach-item hoverable" href={l.url} target="_blank" rel="noopener" style={{ textDecoration: 'none' }}>
                <span className="attach-ic"><Icon.book s={16} /></span>
                <span style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{l.title || l.url}</b></span>
                <span style={{ color: 'var(--accent)', flex: 'none' }}><Icon.arrow s={16} /></span>
              </a>
            ))}
          </div>
        </div>
      )}

      <div style={{ display: 'flex', gap: 10, marginTop: 22, flexWrap: 'wrap' }}>
        {mine
          ? <button className="btn btn-primary" onClick={() => window.printCertificate(c, mine, L)}><Icon.award s={16} /> {t('my_cert')}</button>
          : <a className="btn btn-ghost" href={'#checkin=' + c.id} onClick={onClose}><Icon.check s={16} /> {t('checkin_open')}</a>}
      </div>
    </div>
  );
}

function OnDemandPage({ go, t, L, store }) {
  const toast = useToast();
  const data = store.data;
  const [q, setQ] = React.useState('');
  const [cat, setCat] = React.useState('all');
  const [open, setOpen] = React.useState(null);
  const [editing, setEditing] = React.useState(null);

  const saveMaterial = (m) => {
    const next = structuredClone(data);
    const idx = (next.courses || []).findIndex(x => x.id === m.id);
    if (idx >= 0) next.courses[idx] = m; else next.courses.push(m);
    store.save(next);
    setEditing(null);
    toast(t('mat_saved'));
  };
  const deleteMaterial = (id) => {
    const next = structuredClone(data);
    next.courses = (next.courses || []).filter(x => x.id !== id);
    store.save(next);
    setEditing(null);
    setOpen(null);
  };

  const items = libraryItems(data).filter(({ c }) => {
    if (cat !== 'all' && c.cat !== cat) return false;
    if (!q.trim()) return true;
    const hay = [L(c.title), L(c.presenter), L(c.objective), L(c.outcomes)].join(' ').toLowerCase();
    return hay.includes(q.trim().toLowerCase());
  });
  const nVid = items.filter(({ c }) => c.video).length;
  const nFiles = items.reduce((s, { c }) => s + (c.files || []).length + (c.links || []).length, 0);

  return (
    <div>
      <PageHeader go={go} t={t} eyebrow={t('lib_eyebrow')} title={t('lib_title')} sub={t('lib_sub')} icon="play" />
      <section className="section tight">
        <div className="wrap">
          <div className="grid g4" style={{ gap: 14, marginBottom: 26 }}>
            {[[t('lib_stat_items'), items.length, 'book'], [t('lib_stat_vid'), nVid, 'play'], [t('lib_stat_files'), nFiles, 'layers'], [t('lib_stat_open'), '24/7', 'clock']].map(([lab, val, ic]) => {
              const I = Icon[ic];
              return (
                <div key={lab} className="card card-pad" style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <span className="av" style={{ width: 40, height: 40, background: 'color-mix(in srgb, var(--accent) 16%, transparent)', color: 'var(--accent)', flex: 'none' }}><I s={20} /></span>
                  <div><div style={{ fontSize: 22, fontWeight: 800 }}>{val}</div><div className="muted" style={{ fontSize: 12.5 }}>{lab}</div></div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', gap: 14, justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', marginBottom: 26 }}>
            <div className="tabs">
              {COURSE_CATS.map(c => <button key={c.id} className={"tab " + (cat === c.id ? 'on' : '')} onClick={() => setCat(c.id)}>{L(c.label)}</button>)}
            </div>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
              <input className="input" style={{ maxWidth: 240 }} value={q} onChange={e => setQ(e.target.value)} placeholder={t('lib_search')} />
              <button className="btn btn-primary" onClick={() => setEditing(blankMaterial())}><Icon.plus s={17} /> {t('mat_add')}</button>
            </div>
          </div>

          {items.length === 0 ? (
            <div className="card card-pad center" style={{ padding: 44 }}>
              <span className="av" style={{ width: 60, height: 60, margin: '0 auto 16px', background: 'color-mix(in srgb, var(--accent) 16%, transparent)', color: 'var(--accent)' }}><Icon.play s={28} /></span>
              <h3 style={{ fontSize: 20 }}>{t('lib_empty_t')}</h3>
              <p className="muted" style={{ fontSize: 14.5, marginTop: 10, maxWidth: 520, marginInline: 'auto', lineHeight: 1.7 }}>{t('lib_empty_d')}</p>
              <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={() => setEditing(blankMaterial())}><Icon.plus s={16} /> {t('mat_add')}</button>
            </div>
          ) : (
            <div className="grid g3">
              <button className="card add-tile" onClick={() => setEditing(blankMaterial())}>
                <span className="add-plus"><Icon.plus s={26} /></span>
                <b style={{ fontSize: 16 }}>{t('mat_add')}</b>
                <span className="muted" style={{ fontSize: 13 }}>{t('mat_add_hint')}</span>
              </button>
              {items.map((it, i) => (
                <Reveal key={it.c.id} delay={(i % 3) * 70}><LibraryCard item={it} t={t} L={L} onOpen={() => setOpen(it.c)} onEdit={() => setEditing(structuredClone(it.c))} /></Reveal>
              ))}
            </div>
          )}

          <div className="card card-pad" style={{ marginTop: 30, display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap', background: 'color-mix(in srgb, var(--accent) 8%, transparent)', borderColor: 'color-mix(in srgb, var(--accent) 26%, transparent)' }}>
            <span className="av" style={{ width: 42, height: 42, background: 'var(--accent)', flex: 'none' }}><Icon.clock s={20} /></span>
            <p style={{ flex: 1, minWidth: 240, fontSize: 14.5, lineHeight: 1.7 }}>{t('lib_note')}</p>
          </div>
        </div>
      </section>

      <Modal open={!!open} onClose={() => setOpen(null)} max={760}>
        {open && <LibraryViewer c={open} t={t} L={L} data={data} onClose={() => setOpen(null)} />}
      </Modal>

      <Modal open={!!editing} onClose={() => setEditing(null)} max={660}>
        {editing && <MaterialForm t={t} L={L} item={editing} onSave={saveMaterial} onCancel={() => setEditing(null)}
          onDelete={(data.courses || []).some(x => x.id === editing.id) ? () => deleteMaterial(editing.id) : null} />}
      </Modal>
    </div>
  );
}

Object.assign(window, { OnDemandPage, LibraryCard, LibraryViewer, LinksField, MaterialForm, blankMaterial, embedUrl, libraryItems });
