// pages-b.jsx — AI literacy, Gallery (+GalleryCard), Dashboard, Contact, Footer

/* ============ AI LITERACY ============ */
function AiPage({ go, t, L }) {
  const [open, setOpen] = React.useState(null);
  const [quiz, setQuiz] = React.useState({});
  return (
    <div>
      <PageHeader go={go} t={t} eyebrow={t('ai_eyebrow')} title={t('ai_title')} sub={t('ai_sub')} icon="cpu" />
      <section className="section tight">
        <div className="wrap">
          {/* tracks */}
          <div className="grid g2">
            {AI_TRACKS.map((a, i) => {
              const I = Icon[a.accent === 'purple' ? 'cpu' : a.accent === 'gold' ? 'shield' : 'spark'];
              return (
                <Reveal key={a.id} delay={(i % 2) * 90}>
                  <div className="card hoverable card-pad" style={{ display: 'flex', gap: 18, alignItems: 'flex-start' }}>
                    <span style={{ width: 54, height: 54, flex: 'none', borderRadius: 15, display: 'grid', placeItems: 'center', background: `color-mix(in srgb, var(--${a.accent}) 16%, transparent)`, color: `var(--${a.accent})` }}><I s={26} /></span>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
                        <span className={`badge ${a.accent}`}>{L(a.level)}</span>
                        <span className="chip" style={{ padding: '3px 10px', fontSize: 12 }}><Icon.clock s={12} /> {a.mins} {L({ ar: 'دقيقة', en: 'min' })}</span>
                      </div>
                      <h3 style={{ fontSize: 19 }}>{L(a.title)}</h3>
                      <p className="muted" style={{ fontSize: 14.5, marginTop: 8, lineHeight: 1.6 }}>{L(a.desc)}</p>
                      <button className="btn btn-ghost btn-sm" style={{ marginTop: 14 }} onClick={() => go('courses')}><Icon.play s={14} /> {t('ai_start')}</button>
                    </div>
                  </div>
                </Reveal>
              );
            })}
          </div>

          {/* tip + quiz */}
          <div className="grid g2" style={{ marginTop: 24 }}>
            <Reveal>
              <div className="card card-pad" style={{ background: 'linear-gradient(135deg, color-mix(in srgb, var(--purple) 16%, transparent), transparent)', borderColor: 'color-mix(in srgb, var(--purple) 28%, transparent)' }}>
                <div className="eyebrow" style={{ color: '#b6a4ff' }}><Icon.spark s={15} /> {t('ai_tip_t')}</div>
                <p style={{ fontSize: 18, marginTop: 14, lineHeight: 1.7 }}>{L(AI_TIP)}</p>
              </div>
            </Reveal>
            <Reveal delay={90}>
              <div className="card card-pad">
                <div className="eyebrow"><Icon.target s={15} /> {t('ai_quiz')}</div>
                <div style={{ display: 'grid', gap: 12, marginTop: 16 }}>
                  {AI_QUIZ.map((q, i) => (
                    <div key={i} className="card" style={{ padding: 16, background: 'rgba(255,255,255,.025)' }}>
                      <button className="back-link" style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)', width: '100%', justifyContent: 'space-between', display: 'flex' }} onClick={() => setQuiz(s => ({ ...s, [i]: !s[i] }))}>
                        {L(q.q)} <Icon.chevR s={16} style={{ transform: quiz[i] ? 'rotate(90deg)' : 'none', transition: '.2s' }} />
                      </button>
                      {quiz[i] && <p className="muted" style={{ fontSize: 14.5, marginTop: 10, lineHeight: 1.6 }}><span style={{ color: 'var(--accent)' }}>✓ </span>{L(q.a)}</p>}
                    </div>
                  ))}
                </div>
              </div>
            </Reveal>
          </div>

          {/* glossary */}
          <Reveal>
            <div style={{ marginTop: 36 }}>
              <Head eyebrow={t('ai_glossary')} title={L({ ar: 'مصطلحات تهمّك', en: 'Terms worth knowing' })} icon="book" />
              <div className="grid g2" style={{ marginTop: 24 }}>
                {AI_GLOSSARY.map((g, i) => (
                  <div key={i} className="card card-pad" style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                    <span style={{ color: 'var(--accent)', flex: 'none', marginTop: 2 }}><Icon.hash s={18} /></span>
                    <div><b style={{ fontSize: 16 }}>{L(g.term)}</b><p className="muted" style={{ fontSize: 14, marginTop: 6, lineHeight: 1.6 }}>{L(g.def)}</p></div>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
        </div>
      </section>
    </div>
  );
}

/* ============ GALLERY ============ */
const STATUS_MAP = {
  review: { badge: 'rose', key: 'st_review' },
  pilot: { badge: 'purple', key: 'st_pilot' },
  adopted: { badge: 'mint', key: 'st_adopted' },
};
function GalleryCard({ g, t, L }) {
  const s = STATUS_MAP[g.status];
  return (
    <div className="card hoverable" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <PH h={150} icon="layers" style={{ borderRadius: 0, border: 0, borderBottom: '1px solid var(--line)' }} />
      <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="chip" style={{ padding: '4px 11px', fontSize: 12 }}>{L(g.dept)}</span>
          <span className={`badge ${s.badge}`}>{t(s.key)}</span>
        </div>
        <h3 style={{ fontSize: 18 }}>{L(g.title)}</h3>
        <p className="muted" style={{ fontSize: 14.5, lineHeight: 1.6 }}>{L(g.desc)}</p>
      </div>
    </div>
  );
}

function GalleryPage({ go, t, L }) {
  const [f, setF] = React.useState('all');
  const filters = [
    { id: 'all', label: { ar: 'الكل', en: 'All' } },
    { id: 'adopted', label: { ar: 'مُعتمد', en: 'Adopted' } },
    { id: 'pilot', label: { ar: 'تجربة', en: 'Pilot' } },
    { id: 'review', label: { ar: 'مراجعة', en: 'Review' } },
  ];
  const list = GALLERY.filter(g => f === 'all' || g.status === f);
  return (
    <div>
      <PageHeader go={go} t={t} eyebrow={t('gallery_eyebrow')} title={t('gallery_title')} sub={t('gallery_sub')} icon="grid" />
      <section className="section tight">
        <div className="wrap">
          <div className="tabs" style={{ marginBottom: 28 }}>
            {filters.map(x => <button key={x.id} className={`tab ${f === x.id ? 'on' : ''}`} onClick={() => setF(x.id)}>{L(x.label)}</button>)}
          </div>
          <div className="grid g3">
            {list.map((g, i) => <Reveal key={g.id} delay={(i % 3) * 80}><GalleryCard g={g} t={t} L={L} /></Reveal>)}
          </div>
        </div>
      </section>
      <Dashboard t={t} L={L} embedded />
    </div>
  );
}

/* ============ DASHBOARD ============ */
function Dashboard({ t, L, embedded }) {
  const deptData = [
    [{ ar: 'تجربة الموظف', en: 'Employee experience' }, 68],
    [{ ar: 'الرعاية الأولية', en: 'Primary care' }, 54],
    [{ ar: 'الطوارئ', en: 'Emergency' }, 41],
    [{ ar: 'الصيدلية', en: 'Pharmacy' }, 33],
    [{ ar: 'العيادات الخارجية', en: 'Outpatient' }, 28],
    [{ ar: 'إدارة المرافق', en: 'Facilities' }, 24],
  ];
  const maxV = Math.max(...deptData.map(d => d[1]));
  const statusDist = [
    [{ ar: 'قيد المراجعة', en: 'Under review' }, 112, 'rose'],
    [{ ar: 'تجربة ميدانية', en: 'In pilot' }, 84, 'purple'],
    [{ ar: 'مُعتمد', en: 'Adopted' }, 52, 'mint'],
  ];
  const total = statusDist.reduce((a, b) => a + b[1], 0);
  return (
    <section className="section">
      <div className="wrap">
        <Reveal><Head eyebrow={t('dash_title')} title={t('dash_title')} sub={t('dash_sub')} icon="chart" /></Reveal>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr .9fr', gap: 24, marginTop: 40 }} className="dash-grid">
          <Reveal>
            <div className="card card-pad">
              <div className="eyebrow"><Icon.chart s={15} /> {t('by_dept')}</div>
              <div style={{ display: 'grid', gap: 16, marginTop: 22 }}>
                {deptData.map(([d, v], i) => (
                  <div key={i}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, marginBottom: 6 }}><span>{L(d)}</span><b className="muted">{v}</b></div>
                    <div className="bar"><i style={{ width: (v / maxV * 100) + '%' }} /></div>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
          <Reveal delay={100}>
            <div className="card card-pad">
              <div className="eyebrow"><Icon.target s={15} /> {t('status')}</div>
              <DonutChart data={statusDist} total={total} />
              <div style={{ display: 'grid', gap: 10, marginTop: 18 }}>
                {statusDist.map(([d, v, c], i) => (
                  <div key={i} className="stat-line" style={{ padding: '10px 0' }}>
                    <span style={{ display: 'flex', gap: 9, alignItems: 'center', fontSize: 14.5 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: `var(--${c})` }} /> {L(d)}</span>
                    <b>{v}</b>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
        </div>
      </div>
      <style>{`@media(max-width:820px){.dash-grid{grid-template-columns:1fr!important}}`}</style>
    </section>
  );
}

function DonutChart({ data, total }) {
  const R = 54, C = 2 * Math.PI * R;
  let off = 0;
  const colors = { mint: '#1fd1a3', purple: '#8a6dff', gold: '#e7b34a', rose: '#ff7a8a' };
  return (
    <div style={{ display: 'grid', placeItems: 'center', margin: '20px 0 4px' }}>
      <svg width="160" height="160" viewBox="0 0 140 140" style={{ transform: 'rotate(-90deg)' }}>
        <circle cx="70" cy="70" r={R} fill="none" stroke="rgba(255,255,255,.07)" strokeWidth="18" />
        {data.map(([, v, c], i) => {
          const len = (v / total) * C;
          const el = <circle key={i} cx="70" cy="70" r={R} fill="none" stroke={colors[c]} strokeWidth="18" strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-off} strokeLinecap="butt" />;
          off += len;
          return el;
        })}
      </svg>
      <div style={{ position: 'absolute', textAlign: 'center' }}>
        <div className="kpi-num" style={{ fontSize: 30 }}>{total}</div>
        <div className="muted" style={{ fontSize: 12 }}>{total ? '' : ''}</div>
      </div>
    </div>
  );
}

/* ============ CONTACT ============ */
function waLink(num) {
  const digits = String(num || '').replace(/[^\d]/g, '').replace(/^00/, '');
  return 'https://wa.me/' + digits;
}

function Contact({ t, L, data }) {
  const c = data.contact;
  const items = [
    ['mail', 'ch_email', c.email, `mailto:${c.email}`, null],
    ['wa', 'ch_whatsapp', c.whatsapp, waLink(c.whatsapp), c.lead ? L(c.lead) : null],
    ['phone', 'ch_phone', c.phone, null, null],
    ['pin', 'ch_office', L(c.office), null, null],
  ];
  return (
    <section className="section" id="contact" style={{ background: 'linear-gradient(180deg, transparent, rgba(255,255,255,.02))' }}>
      <div className="wrap">
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }} className="contact-grid">
            <div style={{ padding: 40 }}>
              <div className="eyebrow"><Icon.mail s={15} /> {t('contact_t')}</div>
              <h2 style={{ fontSize: 30, marginTop: 14 }}>{t('contact_t')}</h2>
              <p className="muted" style={{ marginTop: 12, fontSize: 16, lineHeight: 1.7 }}>{t('contact_d')}</p>
              <div style={{ display: 'grid', gap: 14, marginTop: 26 }}>
                {items.map(([ic, lbl, val, href, sub], i) => {
                  const I = Icon[ic];
                  const inner = (
                    <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
                      <span style={{ width: 44, height: 44, flex: 'none', borderRadius: 12, display: 'grid', placeItems: 'center', background: 'rgba(255,255,255,.05)', border: '1px solid var(--line)', color: 'var(--accent)' }}><I s={20} /></span>
                      <div><div className="muted" style={{ fontSize: 12.5 }}>{STR[lbl] ? t(lbl) : lbl}{sub ? ` · ${sub}` : ''}</div><b style={{ fontSize: 15.5, direction: ic === 'wa' || ic === 'phone' ? 'ltr' : 'inherit', display: 'inline-block' }}>{val}</b></div>
                    </div>
                  );
                  return href ? <a key={i} href={href} target={href.startsWith('http') ? '_blank' : undefined} rel="noopener">{inner}</a> : <div key={i}>{inner}</div>;
                })}
              </div>
            </div>
            <div style={{ background: 'linear-gradient(135deg, color-mix(in srgb, var(--mint) 14%, transparent), color-mix(in srgb, var(--purple) 16%, transparent))', display: 'grid', placeItems: 'center', padding: 40, position: 'relative' }} className="dotgrid">
              <div className="center">
                <div className="logo-mark" style={{ width: 72, height: 72, margin: '0 auto 18px', borderRadius: 20 }}>
                  <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="#04201a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18h6M10.5 21h3M12 3a6 6 0 0 0-3.3 11c.5.4.8 1 .8 1.6V16h5v-.4c0-.6.3-1.2.8-1.6A6 6 0 0 0 12 3Z" /></svg>
                </div>
                <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 24 }}>IBTIKAR.HEALTH</div>
                <p className="muted" style={{ marginTop: 8, maxWidth: 260 }}>{L({ ar: 'كل فكرة تستحق أن تُسمع.', en: 'Every idea deserves to be heard.' })}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`@media(max-width:760px){.contact-grid{grid-template-columns:1fr!important}}`}</style>
    </section>
  );
}

/* ============ FOOTER ============ */
function Footer({ t, L, go, data }) {
  const links = [['nav_idea', 'idea'], ['nav_courses', 'courses'], ['nav_academy', 'academy'], ['nav_patents', 'patents'], ['nav_ai', 'ai'], ['nav_admin', 'admin']];
  const c = (data && data.contact) || {};
  return (
    <footer className="footer">
      <div className="wrap">
        {/* live visitor counter */}
        <VisitorCounter t={t} L={L} />
        {/* direct contacts — lead + ambassadors */}
        {(c.whatsapp || c.ambassadorPhone || c.ambassador2) && (
          <div className="card" style={{ padding: 22, marginBottom: 36 }}>
            <div className="eyebrow" style={{ color: 'var(--mint)' }}><Icon.spark s={13} /> {t('footer_contact')}</div>
            <div className="grid g3" style={{ gap: 14, marginTop: 16 }}>
              {[
                { name: c.lead, phone: c.whatsapp, color: 'var(--mint)' },
                { name: c.ambassador, phone: c.ambassadorPhone, color: 'var(--purple)' },
                { name: c.ambassador2, phone: c.ambassador2Phone, color: 'var(--gold)' },
              ].filter(p => p.name).map((p, i) => {
                const inner = (
                  <>
                    <span style={{ width: 48, height: 48, flex: 'none', borderRadius: 14, display: 'grid', placeItems: 'center', background: `color-mix(in srgb, ${p.color} 18%, transparent)`, color: p.color }}>
                      {p.phone ? <Icon.wa s={24} /> : <Icon.user s={24} />}
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 15.5, fontWeight: 700 }}>{L(p.name)}</div>
                      {p.phone && <div className="muted" style={{ fontSize: 13.5, marginTop: 2, direction: 'ltr', display: 'inline-block' }}>{p.phone}</div>}
                    </div>
                    {p.phone && <span style={{ color: p.color, flex: 'none' }}><Icon.arrow s={18} /></span>}
                  </>
                );
                const st = { display: 'flex', alignItems: 'center', gap: 14, padding: 16, textDecoration: 'none' };
                return p.phone
                  ? <a key={i} className="card hoverable wa-cta" href={waLink(p.phone)} target="_blank" rel="noopener" style={st}>{inner}</a>
                  : <div key={i} className="card" style={st}>{inner}</div>;
              })}
            </div>
          </div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 30, flexWrap: 'wrap', alignItems: 'flex-start' }}>
          <div style={{ maxWidth: 320 }}>
            <Logo onClick={() => go('home')} />
            <p className="muted" style={{ fontSize: 13.5, marginTop: 16, lineHeight: 1.7 }}>{t('footer_note')}</p>
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', maxWidth: 420 }}>
            {links.map(([k, pg]) => <button key={k} className="nav-link" onClick={() => go(pg)}>{t(k)}</button>)}
          </div>
        </div>
        <div className="hr" style={{ margin: '28px 0 18px' }} />
        <div className="muted" style={{ fontSize: 13, display: 'flex', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <span>© 2026 · {t('footer_rights')}</span>
          <span style={{ fontFamily: 'Space Grotesk' }}>IBTIKAR.HEALTH</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { AiPage, GalleryPage, GalleryCard, Dashboard, Contact, Footer });
