// pages-a.jsx — Idea submission, Weekly Courses, Patents registry

function PageHeader({ go, t, eyebrow, title, sub, icon }) {
  return (
    <div className="page-head">
      <BrainCanvas mode="backdrop" />
      <div className="wrap">
        <button className="back-link" onClick={() => go('home')}><Icon.arrowL s={16} /> {t('back')}</button>
        <div style={{ marginTop: 22 }}><Head eyebrow={eyebrow} title={title} sub={sub} icon={icon} /></div>
      </div>
    </div>
  );
}

/* ============ IDEA SUBMISSION ============ */
function IdeaPage({ go, t, L, lang, store }) {
  const toast = useToast();
  const [sending, setSending] = React.useState(false);
  const [done, setDone] = React.useState(null);
  const [cat, setCat] = React.useState(0);
  const [f, setF] = React.useState({ name: '', empId: '', dept: '', email: '', title: '', challenge: '', solution: '', impact: '' });
  const [files, setFiles] = React.useState([]);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const submit = (e) => {
    e.preventDefault();
    setSending(true);
    setTimeout(() => {
      const ref = 'IDEA-' + Math.floor(1000 + Math.random() * 9000);
      const record = {
        ref, kind: 'idea',
        category: IDEA_CATS[cat],
        ...f,
        files,
        submittedAt: new Date().toISOString(),
        status: 'review',
      };
      if (store && store.addSubmission) store.addSubmission('ideas', record);
      setSending(false);
      setDone(ref);
      setF({ name: '', empId: '', dept: '', email: '', title: '', challenge: '', solution: '', impact: '' });
      setFiles([]);
      toast(t('thanks_idea'));
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }, 1100);
  };

  if (done) {
    return (
      <div>
        <PageHeader go={go} t={t} eyebrow={t('nav_idea')} title={t('idea_title')} icon="bulb" />
        <section className="section tight">
          <div className="wrap" style={{ maxWidth: 620 }}>
            <div className="card card-pad center" style={{ padding: 48 }}>
              <div className="av" style={{ width: 72, height: 72, margin: '0 auto 20px', background: 'var(--accent)' }}><Icon.check s={36} /></div>
              <h2 style={{ fontSize: 28 }}>{t('thanks_idea')}</h2>
              <p className="muted" style={{ marginTop: 14, fontSize: 16 }}>{t('thanks_idea_d')}</p>
              <div className="chip on" style={{ margin: '20px auto 0', fontSize: 18, padding: '12px 22px' }}><Icon.hash s={16} /> {done}</div>
              <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 28, flexWrap: 'wrap' }}>
                <button className="btn btn-primary" onClick={() => setDone(null)}>{t('another')}</button>
                <button className="btn btn-ghost" onClick={() => go('home')}>{t('back')}</button>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div>
      <PageHeader go={go} t={t} eyebrow={t('nav_idea')} title={t('idea_title')} sub={t('idea_sub')} icon="bulb" />
      <section className="section tight">
        <div className="wrap form-aside" style={{ display: 'grid', gap: 40, alignItems: 'start' }} >
          <form className="card card-pad" style={{ display: 'grid', gap: 18, padding: 30 }} onSubmit={submit}>
            <div className="grid g2" style={{ gap: 18 }}>
              <Field label={t('f_name')} required><input className="input" required value={f.name} onChange={e => set('name', e.target.value)} placeholder="—" /></Field>
              <Field label={t('f_id')} required><input className="input" required value={f.empId} onChange={e => set('empId', e.target.value)} placeholder="EE-0000" /></Field>
            </div>
            <div className="grid g2" style={{ gap: 18 }}>
              <Field label={t('f_dept')} required><input className="input" required value={f.dept} onChange={e => set('dept', e.target.value)} placeholder="—" /></Field>
              <Field label={t('f_email')} required><input className="input" type="email" required value={f.email} onChange={e => set('email', e.target.value)} placeholder="name@ibtikar.health" /></Field>
            </div>
            <Field label={t('f_category')} required>
              <div className="tabs" style={{ display: 'flex' }}>
                {IDEA_CATS.map((c, i) => (
                  <button type="button" key={i} className={`tab ${cat === i ? 'on' : ''}`} onClick={() => setCat(i)}>{L(c)}</button>
                ))}
              </div>
            </Field>
            <Field label={t('f_idea_title')} required><input className="input" required value={f.title} onChange={e => set('title', e.target.value)} placeholder="—" /></Field>
            <Field label={t('f_challenge')} required><textarea className="textarea" required value={f.challenge} onChange={e => set('challenge', e.target.value)} placeholder="—" /></Field>
            <Field label={t('f_solution')} required><textarea className="textarea" required value={f.solution} onChange={e => set('solution', e.target.value)} placeholder="—" /></Field>
            <Field label={t('f_impact')}><textarea className="textarea" style={{ minHeight: 80 }} value={f.impact} onChange={e => set('impact', e.target.value)} placeholder="—" /></Field>
            <AttachField t={t} L={L} label={t('attachments')} hint={t('attach_hint')} value={files} onChange={setFiles} />
            <button className="btn btn-primary btn-lg" disabled={sending} style={{ justifySelf: 'start' }}>
              {sending ? <><span className="spin" /> {t('sending')}</> : <><Icon.arrow s={18} /> {t('submit')}</>}
            </button>
          </form>

          <aside style={{ display: 'grid', gap: 18, position: 'sticky', top: 90 }}>
            <div className="card card-pad">
              <div className="eyebrow"><Icon.layers s={15} /> {t('proc_title')}</div>
              <div style={{ marginTop: 16, display: 'grid', gap: 14 }}>
                {['proc_1t', 'proc_2t', 'proc_3t', 'proc_4t', 'proc_5t'].map((k, i) => (
                  <div key={k} style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                    <span className="av" style={{ width: 30, height: 30, fontSize: 12, background: i === 0 ? 'var(--accent)' : 'rgba(255,255,255,.08)', color: i === 0 ? 'var(--on-accent)' : 'var(--muted)' }}>{i + 1}</span>
                    <span style={{ fontWeight: 600, fontSize: 15, color: i === 0 ? 'var(--text)' : 'var(--muted)' }}>{t(k)}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="card card-pad" style={{ background: 'color-mix(in srgb, var(--accent) 10%, transparent)', borderColor: 'color-mix(in srgb, var(--accent) 30%, transparent)' }}>
              <Icon.spark s={22} />
              <p style={{ marginTop: 12, fontSize: 14.5, lineHeight: 1.7 }}>{L({ ar: 'الأفكار الأكثر تأثيراً تبدأ من تحدٍّ واضح تعيشه يومياً. صف المشكلة قبل الحل.', en: 'The most impactful ideas start from a clear daily challenge. Describe the problem before the solution.' })}</p>
            </div>
          </aside>
        </div>
      </section>
    </div>
  );
}

/* ============ WEEKLY COURSES ============ */
function CoursesPage({ go, t, L, store }) {
  const toast = useToast();
  const data = store.data;
  const [term, setTerm] = React.useState('upcoming');
  const [filter, setFilter] = React.useState('all');
  const [regs, setRegs] = React.useState(() => myRegs());
  const [details, setDetails] = React.useState(null);
  const [editing, setEditing] = React.useState(null); // course object (new or existing) or null
  const [enrolling, setEnrolling] = React.useState(null);
  const soon = useCourseReminders(data, L);

  const norm = (c) => ((c.term || 'upcoming') === 'past' ? 'past' : 'upcoming');
  const list = data.courses.filter((c) => norm(c) === term && (filter === 'all' || c.cat === filter));

  const isReg = (id) => regs.includes(id);
  const enroll = (c) => {
    if (c.link) { window.open(c.link, '_blank', 'noopener'); return; }
    setEnrolling(c);
  };
  const enrolled = (rec) => {
    setRegs(myRegs());
    setEnrolling(null);
    setDetails(null);
  };

  const saveCourse = (course) => {
    const next = structuredClone(data);
    const idx = next.courses.findIndex(x => x.id === course.id);
    if (idx >= 0) next.courses[idx] = course; else next.courses.push(course);
    store.save(next);
    setEditing(null);
    setDetails(null);
    toast(t('course_saved'));
  };
  const removeCourse = (id) => {
    const next = structuredClone(data);
    next.courses = next.courses.filter(c => c.id !== id);
    store.save(next);
    setDetails(null);
  };
  const startAdd = () => setEditing(blankCourse(term));

  return (
    <div>
      <PageHeader go={go} t={t} eyebrow={t('courses_eyebrow')} title={t('courses_title')} sub={term === 'past' ? t('past_sub') : t('upcoming_sub')} icon="book" />
      <section className="section tight">
        <div className="wrap">
          <ReminderBanner soon={soon} t={t} L={L} />
          <LiveCourseBar data={data} store={store} t={t} L={L} />
          {/* primary toggle: upcoming / past */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginBottom: 22 }}>
            <div className="tabs">
              <button className={"tab " + (term === 'upcoming' ? 'on' : '')} onClick={() => { setTerm('upcoming'); setFilter('all'); }}><Icon.rocket s={15} style={{ verticalAlign: 'middle', marginInlineEnd: 6 }} />{t('courses_upcoming')}</button>
              <button className={"tab " + (term === 'past' ? 'on' : '')} onClick={() => { setTerm('past'); setFilter('all'); }}><Icon.clock s={15} style={{ verticalAlign: 'middle', marginInlineEnd: 6 }} />{t('courses_past')}</button>
            </div>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <button className="btn btn-ghost" onClick={() => go('ondemand')}><Icon.play s={16} /> {t('nav_ondemand')}</button>
              <button className="btn btn-primary" onClick={startAdd}><Icon.plus s={17} /> {term === 'past' ? t('add_past_course') : t('add_upcoming')}</button>
            </div>
          </div>

          {/* category filter */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginBottom: 28 }}>
            <div className="tabs">
              {COURSE_CATS.map((c) => (
                <button key={c.id} className={"tab " + (filter === c.id ? 'on' : '')} onClick={() => setFilter(c.id)}>{L(c.label)}</button>
              ))}
            </div>
            <div className="chip"><Icon.book s={14} /> {list.length} {L({ ar: 'دورة', en: 'courses' })}</div>
          </div>

          <div className="grid g3">
            {/* add tile */}
            <button className="card add-tile" onClick={startAdd}>
              <span className="add-plus"><Icon.plus s={26} /></span>
              <b style={{ fontSize: 16 }}>{term === 'past' ? t('add_past_course') : t('add_upcoming')}</b>
              <span className="muted" style={{ fontSize: 13 }}>{t('add_card_hint')}</span>
            </button>

            {list.map((c, idx) => (
              <Reveal key={c.id} delay={(idx % 3) * 70}>
                <CourseCard c={c} t={t} L={L} registered={isReg(c.id)} onEnroll={() => enroll(c)} onView={() => setDetails(c)} />
              </Reveal>
            ))}
          </div>

          {list.length === 0 && (
            <p className="muted center" style={{ marginTop: 26, fontSize: 15 }}>{term === 'past' ? t('empty_past') : t('empty_new')}</p>
          )}
        </div>
      </section>

      {/* details modal */}
      <Modal open={!!details} onClose={() => setDetails(null)} max={640}>
        {details && (
          <CourseDetails c={details} t={t} L={L} data={data} registered={isReg(details.id)}
            onEnroll={() => enroll(details)} onEdit={() => setEditing(details)} onDelete={() => removeCourse(details.id)} onClose={() => setDetails(null)} />
        )}
      </Modal>

      {/* registration modal */}
      <Modal open={!!enrolling} onClose={() => setEnrolling(null)} max={600}>
        {enrolling && <EnrollModal course={enrolling} t={t} L={L} store={store} onClose={() => setEnrolling(null)} onDone={enrolled} />}
      </Modal>

      {/* add / edit form */}
      <Modal open={!!editing} onClose={() => setEditing(null)} max={640}>
        {editing && <CourseForm t={t} L={L} course={editing} onSave={saveCourse} onCancel={() => setEditing(null)} />}
      </Modal>
    </div>
  );
}

function blankCourse(term) {
  const t = term === 'past' ? 'past' : 'upcoming';
  const base = { id: (t === 'past' ? 'p' : 'u') + Date.now(), term: t, title: '', presenter: '', date: '', startAt: '', objective: '', target: '', outcomes: '', cat: 'innovation', mode: 'onsite', dur: '', accent: t === 'past' ? 'mint' : 'gold', files: [], links: [], video: '' };
  if (t !== 'past') base.link = '';
  return base;
}

function MetaRow({ icon, label, value }) {
  const I = Icon[icon] || Icon.hash;
  return (
    <div style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
      <span style={{ color: 'var(--accent)', flex: 'none', marginTop: 2 }}><I s={15} /></span>
      <div><div className="muted" style={{ fontSize: 12 }}>{label}</div><div style={{ fontSize: 14.5, fontWeight: 600 }}>{value}</div></div>
    </div>
  );
}

function CourseCard({ c, t, L, registered, onEnroll, onView }) {
  const isPast = (c.term || 'upcoming') === 'past';
  const live = window.courseStatus && window.courseStatus(c) === 'live';
  return (
    <div className="card hoverable" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', borderColor: live ? 'color-mix(in srgb, var(--rose) 45%, transparent)' : undefined }}>
      <div style={{ position: 'relative' }}>
        <PH h={120} label={null} icon="book" style={{ borderRadius: 0, borderLeft: 0, borderRight: 0, borderTop: 0, opacity: isPast ? .8 : 1 }} />
        <span className={"badge " + (live ? 'rose' : isPast ? 'mint' : 'gold')} style={{ position: 'absolute', insetInlineEnd: 12, top: 12, backdropFilter: 'blur(6px)', gap: 7 }}>
          {live ? <><span className="live-dot" /> {t('live_now')}</> : isPast ? <><Icon.check s={13} /> {t('completed')}</> : <><Icon.rocket s={13} /> {t('soon')}</>}
        </span>
      </div>
      <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', flex: 1, gap: 12 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <span className={"badge " + c.accent}>{L(COURSE_CATS.find(x => x.id === c.cat)?.label)}</span>
          {c.date && <span className="chip" style={{ padding: '4px 10px', fontSize: 12 }}><Icon.clock s={12} /> {L(c.date)}</span>}
        </div>
        <h3 style={{ fontSize: 18, minHeight: 44 }}>{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.5, display: 'flex', flexDirection: 'column', gap: 6 }}>
          {c.presenter && <span style={{ display: 'flex', gap: 7, alignItems: 'center' }}><Icon.user s={14} /> {L(c.presenter)}</span>}
          {(c.target || c.target === 0) && c.target !== '' && <span style={{ display: 'flex', gap: 7, alignItems: 'center' }}><Icon.users s={14} /> {t('target_emp')}: {c.target}</span>}
        </div>
        <div style={{ marginTop: 'auto', display: 'flex', gap: 10, paddingTop: 6 }}>
          {!isPast && (
            <button className={"btn " + (registered ? 'btn-dark' : 'btn-primary')} style={{ flex: 1 }} onClick={onEnroll}>
              {registered && !c.link ? <><Icon.check s={16} /> {t('registered')}</> : <><Icon.arrow s={15} /> {t('reg_now')}</>}
            </button>
          )}
          <button className="btn btn-ghost" style={{ flex: isPast ? 1 : 'none' }} onClick={onView}>{t('view_details')}</button>
        </div>
      </div>
    </div>
  );
}

function CourseDetails({ c, t, L, data, registered, onEnroll, onEdit, onDelete, onClose }) {
  const toast = useToast();
  const isPast = (c.term || 'upcoming') === 'past';
  const rows = window.regsFor ? window.regsFor(data || {}, c.id) : [];
  const present = rows.filter(r => r.attended).length;
  const checkinUrl = location.origin + location.pathname + '#checkin=' + c.id;
  return (
    <div className="card-pad" style={{ padding: 30 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <div className={"badge " + c.accent}><Icon.book s={13} /> {L(COURSE_CATS.find(x => x.id === c.cat)?.label)}</div>
          <div className={"badge " + (isPast ? 'mint' : 'gold')}>{isPast ? <><Icon.check s={13} /> {t('completed')}</> : <><Icon.rocket s={13} /> {t('soon')}</>}</div>
          {window.courseStatus && window.courseStatus(c) === 'live' && <div className="badge rose" style={{ gap: 7 }}><span className="live-dot" /> {t('live_now')}</div>}
        </div>
        <button className="btn btn-dark btn-sm" onClick={onClose} style={{ padding: 8 }}><Icon.x s={16} /></button>
      </div>
      <h3 style={{ fontSize: 23, marginTop: 14 }}>{L(c.title)}</h3>
      {c.objective && <p className="muted" style={{ fontSize: 15, marginTop: 10, lineHeight: 1.7 }}>{L(c.objective)}</p>}

      <div className="grid g2" style={{ gap: 14, marginTop: 20 }}>
        {c.presenter && <MetaRow icon="user" label={t('presenter')} value={L(c.presenter)} />}
        {c.date && <MetaRow icon="clock" label={isPast ? t('held_on') : t('course_date')} value={L(c.date)} />}
        {c.dur && <MetaRow icon="clock" label={t('duration')} value={L(c.dur)} />}
        {c.mode && <MetaRow icon={c.mode === 'onsite' ? 'pin' : 'globe'} label={L({ ar: 'النمط', en: 'Mode' })} value={c.mode === 'onsite' ? t('mode_onsite') : t('mode_virtual')} />}
        {c.target !== '' && c.target != null && <MetaRow icon="users" label={t('target_emp')} value={c.target} />}
        {c.rating && <MetaRow icon="award" label={t('rating')} value={'★ ' + c.rating} />}
      </div>

      {c.outcomes && (
        <div style={{ marginTop: 18 }}>
          <div className="eyebrow"><Icon.target s={14} /> {t('outcomes')}</div>
          <p style={{ fontSize: 14.5, 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('attachments')} · {c.files.length}</div>
          <div style={{ marginTop: 10 }}><AttachList items={c.files} L={L} /></div>
        </div>
      )}

      {/* registration · attendance · certificates */}
      <div style={{ marginTop: 20, padding: 16, border: '1px solid var(--line)', borderRadius: 'var(--r)', background: 'rgba(255,255,255,.02)' }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <div className="eyebrow" style={{ margin: 0 }}><Icon.users s={14} /> {t('admin_regs')}</div>
          <span className="chip" style={{ padding: '4px 10px', fontSize: 12 }}>{t('registered_n')}: {rows.length}</span>
          <span className="chip" style={{ padding: '4px 10px', fontSize: 12 }}>{t('attended_n')}: {present}</span>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 12 }}>
          <button className="btn btn-ghost btn-sm" onClick={() => window.printRegistrations(c, rows, L)}><Icon.book s={15} /> {t('pdf_regs')}</button>
          <button className="btn btn-ghost btn-sm" onClick={() => window.printAttendance(c, rows, L)}><Icon.check s={15} /> {t('pdf_attend')}</button>
          <button className="btn btn-ghost btn-sm" disabled={!present} onClick={() => window.printCertificates(c, rows.filter(r => r.attended), L)}><Icon.award s={15} /> {t('print_all_certs')} ({present})</button>
          <a className="btn btn-ghost btn-sm" href={'#checkin=' + c.id} onClick={onClose}><Icon.arrow s={15} /> {t('checkin_eyebrow')}</a>
          <button className="btn btn-ghost btn-sm" onClick={() => { copyText(checkinUrl); toast(t('link_copied')); }}><Icon.hash s={15} /> {t('copy_checkin')}</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 10, marginTop: 24, flexWrap: 'wrap' }}>
        {!isPast && (
          <button className={"btn " + (registered && !c.link ? 'btn-dark' : 'btn-primary')} style={{ flex: 1, minWidth: 160 }} onClick={onEnroll}>
            {registered && !c.link ? <><Icon.check s={16} /> {t('registered')}</> : <><Icon.arrow s={16} /> {t('reg_now')}</>}
          </button>
        )}
        <button className="btn btn-ghost" onClick={onEdit}><Icon.pen s={15} /> {t('edit')}</button>
        <button className="btn btn-dark" onClick={onDelete} style={{ color: 'var(--rose)' }}><Icon.trash s={15} /></button>
      </div>
    </div>
  );
}

/* ---- shared course registration form (used by Courses page & Admin) ---- */
function CourseForm({ t, L, course, onSave, onCancel }) {
  const [c, setC] = React.useState(course);
  const isPast = (c.term || 'upcoming') === 'past';
  const upd = (k, v) => setC(s => ({ ...s, [k]: v }));
  const valid = String(c.title).trim() && String(c.presenter).trim() && String(c.date).trim();
  return (
    <div className="card-pad" style={{ padding: 28 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
        <div>
          <div className="eyebrow"><Icon.book s={14} /> {isPast ? t('courses_past') : t('courses_upcoming')}</div>
          <h3 style={{ fontSize: 21, marginTop: 6 }}>{String(course.title).trim() ? t('edit_course') : t('reg_a_course')}</h3>
        </div>
        <button className="btn btn-dark btn-sm" onClick={onCancel} style={{ padding: 8 }}><Icon.x s={16} /></button>
      </div>

      <div style={{ display: 'grid', gap: 16, marginTop: 20 }}>
        <Field label={t('course_name')} required><input className="input" value={c.title} onChange={e => upd('title', e.target.value)} placeholder={L({ ar: 'مثال: أساسيات الابتكار في الخدمات الصحية', en: 'e.g. Innovation basics in health services' })} /></Field>
        <div className="grid g2" style={{ gap: 16 }}>
          <Field label={t('presenter')} required><input className="input" value={c.presenter} onChange={e => upd('presenter', e.target.value)} placeholder={L({ ar: 'اسم المدرّب أو الجهة', en: 'Trainer or entity' })} /></Field>
          <Field label={isPast ? t('held_on') : t('course_date')} required><input className="input" value={c.date} onChange={e => upd('date', e.target.value)} placeholder={L({ ar: '١٥ يونيو ٢٠٢٦', en: '15 June 2026' })} /></Field>
        </div>
        <Field label={t('objective')} required><textarea className="textarea" value={c.objective} onChange={e => upd('objective', e.target.value)} placeholder={L({ ar: 'ما الذي ستحققه هذه الدورة؟', en: 'What will this course achieve?' })} /></Field>
        <div className="grid g2" style={{ gap: 16 }}>
          <Field label={t('target_emp')} required><input className="input" type="number" min="0" value={c.target} onChange={e => upd('target', e.target.value === '' ? '' : +e.target.value)} placeholder="30" /></Field>
          <Field label={t('duration')}><input className="input" value={c.dur} onChange={e => upd('dur', e.target.value)} placeholder={L({ ar: '٣ ساعات', en: '3 hours' })} /></Field>
        </div>
        <Field label={t('outcomes')}><textarea className="textarea" value={c.outcomes} onChange={e => upd('outcomes', e.target.value)} placeholder={L({ ar: 'المهارات أو النواتج التي يخرج بها المتدرب', en: 'Skills or deliverables the trainee gains' })} /></Field>
        {!isPast && (
          <Field label={t('course_start')} hint={t('course_start_hint')}>
            <input className="input" type="datetime-local" value={c.startAt || ''} onChange={e => upd('startAt', e.target.value)} dir="ltr" style={{ textAlign: 'start' }} />
          </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>
        <AttachField t={t} L={L} label={t('attachments')} hint={t('attach_hint')} value={c.files || []} onChange={(v) => upd('files', v)} />
        <LinksField L={L} label={t('course_links')} hint={t('course_links_hint')} value={c.links || []} onChange={(v) => upd('links', v)} />
        <div className="grid g3" 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: 'Mode' })}>
            <select className="select" value={c.mode} onChange={e => upd('mode', e.target.value)}>
              <option value="onsite">{t('mode_onsite')}</option><option value="virtual">{t('mode_virtual')}</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>
        {!isPast && (
          <Field label={t('reg_link')} hint={L({ ar: 'رابط خارجي للتسجيل (نموذج، تيمز، إلخ) — إن تُرك فارغاً يُسجّل الموظف داخل المنصة.', en: 'External registration URL — if empty, employees register in-app.' })}>
            <input className="input" value={c.link || ''} onChange={e => upd('link', e.target.value)} placeholder="https://" dir="ltr" style={{ textAlign: 'start' }} />
          </Field>
        )}
      </div>

      <div style={{ display: 'flex', gap: 12, marginTop: 24, justifyContent: 'flex-end' }}>
        <button className="btn btn-dark" onClick={onCancel}>{t('cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onSave({ ...c, target: c.target === '' ? '' : +c.target })}><Icon.check s={16} /> {t('save')}</button>
      </div>
    </div>
  );
}


/* ============ PATENTS ============ */
function PatentsPage({ go, t, L, lang, store }) {
  const toast = useToast();
  const [sending, setSending] = React.useState(false);
  const [done, setDone] = React.useState(null);
  const [stage, setStage] = React.useState(0);
  const [f, setF] = React.useState({ title: '', inventors: '', field: '', abstract: '', novelty: '' });
  const [files, setFiles] = React.useState([]);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const submit = (e) => {
    e.preventDefault();
    setSending(true);
    setTimeout(async () => {
      const ref = 'IP-' + new Date().getFullYear() + '-' + Math.floor(100 + Math.random() * 900);
      const record = {
        ref, kind: 'patent',
        ...f,
        files,
        stage: PATENT_STAGES[stage],
        submittedAt: new Date().toISOString(),
        status: 'review',
      };
      if (store && store.addSubmission) store.addSubmission('patents', record);
      // seal it into the innovation vault the moment it lands
      let seal = null;
      try { seal = await sealDisclosure(record); } catch (err) { seal = null; }
      if (seal && store && store.putSeal) store.putSeal(ref, seal);
      setSending(false);
      setDone({ ref, seal });
      setF({ title: '', inventors: '', field: '', abstract: '', novelty: '' });
      setFiles([]);
      toast(t('thanks_patent'));
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }, 1100);
  };

  const steps = [
    [L({ ar: 'كشف الاختراع', en: 'Disclosure' }), L({ ar: 'وثّق فكرتك سرياً', en: 'Document confidentially' }), 'pen'],
    [L({ ar: 'بحث حالة تقنية', en: 'Prior-art search' }), L({ ar: 'نتأكد من الجدّة', en: 'We verify novelty' }), 'target'],
    [L({ ar: 'صياغة الطلب', en: 'Drafting' }), L({ ar: 'مع وكيل براءات', en: 'With a patent agent' }), 'pen'],
    [L({ ar: 'الإيداع', en: 'Filing' }), L({ ar: 'لدى الهيئة المختصة', en: 'At the authority' }), 'shield'],
    [L({ ar: 'المنح', en: 'Grant' }), L({ ar: 'حماية معتمدة', en: 'Protected IP' }), 'award'],
  ];

  if (done) {
    return (
      <div>
        <PageHeader go={go} t={t} eyebrow={t('nav_patents')} title={t('patents_title')} icon="award" />
        <section className="section tight">
          <div className="wrap" style={{ maxWidth: 620 }}>
            <div className="card card-pad center" style={{ padding: 48 }}>
              <div className="av" style={{ width: 72, height: 72, margin: '0 auto 20px', background: 'var(--gold)' }}><Icon.shield s={34} /></div>
              <h2 style={{ fontSize: 28 }}>{t('thanks_patent')}</h2>
              <p className="muted" style={{ marginTop: 14, fontSize: 16 }}>{t('thanks_patent_d')}</p>
              <div className="chip on" style={{ margin: '20px auto 0', fontSize: 18, padding: '12px 22px' }}><Icon.hash s={16} /> {done.ref}</div>
              {done.seal && (
                <div className="seal-hero" style={{ marginTop: 24, textAlign: 'start' }}>
                  <FingerprintGlyph code={done.seal.fingerprint} size={70} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div className="muted" style={{ fontSize: 12 }}>{t('vlt_your_fp')}</div>
                    <div className="seal-code big" dir="ltr">{done.seal.fingerprint}</div>
                    <div className="muted" style={{ fontSize: 12, marginTop: 6 }} dir="ltr">{new Date(done.seal.sealedAt).toISOString().replace('T', ' ').slice(0, 19)} UTC</div>
                  </div>
                </div>
              )}
              <p className="muted" style={{ fontSize: 13, marginTop: 14, lineHeight: 1.6 }}>{t('vlt_sealed_note')}</p>
              <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 28, flexWrap: 'wrap' }}>
                <button className="btn btn-primary" onClick={() => setDone(null)}>{L({ ar: 'كشف آخر', en: 'New disclosure' })}</button>
                <button className="btn btn-ghost" onClick={() => go('home')}>{t('back')}</button>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div>
      <PageHeader go={go} t={t} eyebrow={t('nav_patents')} title={t('patents_title')} sub={t('patents_sub')} icon="award" />
      <section className="section tight">
        <div className="wrap">
          <Reveal>
            <div className="card card-pad" style={{ marginBottom: 36 }}>
              <div className="eyebrow"><Icon.shield s={15} /> {t('ip_steps_t')}</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 12, marginTop: 22 }} className="proc-grid">
                {steps.map(([tt, dd, ic], i) => {
                  const I = Icon[ic];
                  return (
                    <div key={i} style={{ position: 'relative' }}>
                      <span style={{ width: 44, height: 44, borderRadius: 12, display: 'grid', placeItems: 'center', background: 'color-mix(in srgb, var(--gold) 16%, transparent)', color: 'var(--gold)' }}><I s={22} /></span>
                      <div style={{ fontWeight: 700, fontSize: 15, marginTop: 12 }}>{tt}</div>
                      <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{dd}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </Reveal>

          <div className="form-aside" style={{ display: 'grid', gap: 40, alignItems: 'start' }}>
            <form className="card card-pad" style={{ display: 'grid', gap: 18, padding: 30 }} onSubmit={submit}>
              <Field label={t('pf_title')} required><input className="input" required value={f.title} onChange={e => set('title', e.target.value)} placeholder="—" /></Field>
              <Field label={t('pf_inventors')} required><input className="input" required value={f.inventors} onChange={e => set('inventors', e.target.value)} placeholder="—" /></Field>
              <Field label={t('pf_field')} required><input className="input" required value={f.field} onChange={e => set('field', e.target.value)} placeholder="—" /></Field>
              <Field label={t('pf_abstract')} required><textarea className="textarea" required value={f.abstract} onChange={e => set('abstract', e.target.value)} placeholder="—" /></Field>
              <Field label={t('pf_novel')} required><textarea className="textarea" style={{ minHeight: 90 }} required value={f.novelty} onChange={e => set('novelty', e.target.value)} placeholder="—" /></Field>
              <Field label={t('pf_stage')} required>
                <div className="tabs" style={{ display: 'flex', flexWrap: 'wrap' }}>
                  {PATENT_STAGES.map((s, i) => (
                    <button type="button" key={i} className={`tab ${stage === i ? 'on' : ''}`} onClick={() => setStage(i)}>{L(s)}</button>
                  ))}
                </div>
              </Field>
              <AttachField t={t} L={L} label={t('attachments')} hint={t('attach_hint_ip')} value={files} onChange={setFiles} />
              <button className="btn btn-primary btn-lg" disabled={sending} style={{ justifySelf: 'start' }}>
                {sending ? <><span className="spin" /> {t('sending')}</> : <><Icon.shield s={18} /> {L({ ar: 'تقديم كشف الاختراع', en: 'Submit disclosure' })}</>}
              </button>
            </form>
            <aside className="card card-pad" style={{ position: 'sticky', top: 90, background: 'color-mix(in srgb, var(--gold) 8%, transparent)', borderColor: 'color-mix(in srgb, var(--gold) 26%, transparent)' }}>
              <Icon.shield s={24} />
              <h3 style={{ fontSize: 19, marginTop: 12 }}>{L({ ar: 'لماذا توثّق مبكراً؟', en: 'Why disclose early?' })}</h3>              <ul style={{ margin: '14px 0 0', padding: 0, listStyle: 'none', display: 'grid', gap: 12 }}>
                {[
                  L({ ar: 'يثبت تاريخ ابتكارك ويحمي أولويتك.', en: 'Establishes your invention date and priority.' }),
                  L({ ar: 'تجنّب النشر العلني قبل الإيداع.', en: 'Avoid public disclosure before filing.' }),
                  L({ ar: 'فريق متخصص يرافقك في كل خطوة.', en: 'A specialist team guides every step.' }),
                ].map((x, i) => (
                  <li key={i} style={{ display: 'flex', gap: 10, fontSize: 14.5, lineHeight: 1.6 }}><span style={{ color: 'var(--gold)', flex: 'none' }}><Icon.check s={18} /></span>{x}</li>
                ))}
              </ul>
              <div className="conf-note">
                <Icon.shield s={16} /> {t('patents_private')}
              </div>
              <div className="conf-note" style={{ paddingTop: 12, marginTop: 12 }}>
                <Icon.lock s={16} /> {t('vlt_sealed_note')}
              </div>
            </aside>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { IdeaPage, CoursesPage, PatentsPage, CourseCard, CourseDetails, CourseForm, blankCourse, MetaRow, PageHeader });
