/* OpenMedEdu — shared production components. */

function goTo(route) {
  if (typeof window !== 'undefined' && window.__ome_navigate) {
    window.__ome_navigate(route);
  }
}

// ─────────────────────────────────────────────────────────────
// NavBar — sticky header with mobile drawer
// ─────────────────────────────────────────────────────────────
function NavBar({ active }) {
  const t = useT();
  const [drawer, setDrawer] = React.useState(false);

  React.useEffect(() => {
    if (drawer) {
      const onKey = (e) => { if (e.key === 'Escape') setDrawer(false); };
      window.addEventListener('keydown', onKey);
      document.body.style.overflow = 'hidden';
      return () => {
        window.removeEventListener('keydown', onKey);
        document.body.style.overflow = '';
      };
    }
  }, [drawer]);

  const navItems = [
    { key: 'catalogue', label: t('catalogue'), route: 'catalogue' },
    { key: 'courses',   label: t('courses'),   route: 'catalogue' },
    { key: 'articles',  label: t('articles'),  route: 'article' },
    { key: 'news',      label: t('news'),      route: 'catalogue' },
    { key: 'specs',     label: t('specs'),     route: 'catalogue' },
    { key: 'teams',     label: t('teams'),     route: 'catalogue' },
    { key: 'about',     label: t('about'),     route: 'catalogue', muted: true },
  ];

  const navigate = (route) => {
    setDrawer(false);
    goTo(route);
  };

  return (
    <header className="site-header">
      <div className="container nav-row">
        <a className="nav-brand" onClick={() => navigate('home')}>
          <span className="brand-mark">+</span>
          <span>OpenMedEdu</span>
        </a>

        <nav className="nav-links" aria-label="Primary">
          {navItems.map((item) => (
            <a
              key={item.key}
              onClick={() => navigate(item.route)}
              className={[
                active === item.key ? 'is-active' : '',
                item.muted ? 'is-muted' : '',
              ].join(' ').trim()}
            >
              {item.label}
            </a>
          ))}
        </nav>

        <div className="nav-actions">
          <button
            className="nav-search-trigger"
            onClick={() => navigate('catalogue')}
            aria-label={t('search')}
          >
            <span>⌕</span>
            <span>{t('search')}</span>
            <span className="nav-kbd">⌘K</span>
          </button>
          <LangPicker />
          <button className="btn btn-sky hide-mobile" onClick={() => navigate('signup')}>
            <span>{t('login_register')}</span>
          </button>
          <button
            className="nav-burger"
            aria-label="Menu"
            aria-expanded={drawer}
            onClick={() => setDrawer(true)}
          >
            <span />
          </button>
        </div>
      </div>

      <div className={'mobile-drawer ' + (drawer ? 'is-open' : '')} aria-hidden={!drawer}>
        <div className="backdrop" onClick={() => setDrawer(false)} />
        <div className="panel" role="dialog" aria-modal="true">
          <header>
            <a className="nav-brand" onClick={() => navigate('home')}>
              <span className="brand-mark">+</span>
              <span>OpenMedEdu</span>
            </a>
            <button className="btn btn-ghost" aria-label="Close" onClick={() => setDrawer(false)}>✕</button>
          </header>
          {navItems.map((item) => (
            <a key={item.key} onClick={() => navigate(item.route)}>{item.label}</a>
          ))}
          <button className="btn btn-sky btn-block btn-lg" onClick={() => navigate('signup')}>
            {t('login_register')}
          </button>
        </div>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────
// Sub-specialty data (illustrative)
// ─────────────────────────────────────────────────────────────
const SUBSPEC = {
  'Cardiology': ['Interventional', 'Electrophysiology', 'Heart Failure', 'Preventive', 'Cardiac Imaging', 'Adult Congenital'],
  'Internal Medicine': ['General IM', 'Hospital Medicine', 'Ambulatory', 'Transitions of Care'],
  'Pediatrics': ['Neonatology', 'Pediatric Cardiology', 'Adolescent Med', 'Developmental', 'Pediatric ID'],
  'Neurology': ['Stroke', 'Movement Disorders', 'Epilepsy', 'Headache', 'Neuro-Immunology', 'Neuro-Oncology'],
  'General Surgery': ['Trauma', 'Bariatric', 'Colorectal', 'Surgical Oncology', 'Endocrine Surgery'],
  'Radiology': ['Body', 'Neuro', 'Musculoskeletal', 'Pediatric Radio', 'Breast Imaging'],
  'Psychiatry': ['Child & Adolescent', 'Geriatric', 'Addiction', 'Forensic', 'Consult-Liaison'],
  'Oncology': ['Medical Oncology', 'Radiation Oncology', 'Surgical Oncology', 'Hematology-Oncology'],
  'Emergency Medicine': ['Pediatric EM', 'Toxicology', 'Ultrasound', 'Sports EM', 'EMS'],
  'Family Medicine': ['Obstetrical FM', 'Geriatric FM', 'Sports FM', 'Rural Health'],
  'კარდიოლოგია': ['ინტერვენციული', 'ელექტროფიზიოლოგია', 'გულის უკმარისობა', 'პრევენციული', 'კარდიო-გამოსახულება', 'მოზრდილთა თანდაყოლილი'],
  'შინაგანი მედიცინა': ['ზოგადი შინაგანი', 'ჰოსპიტალური', 'ამბულატორიული', 'მოვლის გადაცემები'],
  'პედიატრია': ['ნეონატოლოგია', 'პედიატრიული კარდიო', 'მოზარდთა მედიცინა', 'განვითარების', 'პედიატრიული ID'],
  'ნევროლოგია': ['ინსულტი', 'მოძრაობის დარღვევები', 'ეპილეფსია', 'თავის ტკივილი', 'ნეირო-იმუნოლოგია', 'ნეიროონკოლოგია'],
  'ზოგადი ქირურგია': ['ტრავმა', 'ბარიატრიული', 'კოლორექტული', 'ქირურგიული ონკოლოგია', 'ენდოკრინული ქირურგია'],
  'რადიოლოგია': ['სხეული', 'ნეირო', 'მუსკულოსკელეტური', 'პედიატრიული რადიო', 'ძუძუს გამოსახულება'],
  'ფსიქიატრია': ['ბავშვ-მოზარდთა', 'გერიატრიული', 'ნარკოლოგია', 'სასამართლო', 'კონსულტ-ლეზონი'],
  'ონკოლოგია': ['სამედიცინო ონკოლოგია', 'რადიოონკოლოგია', 'ქირურგიული ონკოლოგია', 'ჰემატო-ონკოლოგია'],
  'გადაუდებელი მედიცინა': ['პედიატრიული EM', 'ტოქსიკოლოგია', 'ულტრაბგერა', 'სპორტული EM', 'EMS'],
  'ოჯახის მედიცინა': ['სამეანო FM', 'გერიატრიული FM', 'სპორტული FM', 'სოფლის ჯანდაცვა'],
};
const SUBSPEC_DEFAULT = ['General', 'Advanced topics', 'Procedures', 'Board review'];

// ─────────────────────────────────────────────────────────────
// SpecialtyGrid — collapsible, click-to-reveal
// ─────────────────────────────────────────────────────────────
function SpecialtyGrid({ count = 48, initialVisible = 16, withCount = true }) {
  const t = useT();
  const all = useSpecialties();
  const items = all.slice(0, count);
  const [expanded, setExpanded] = React.useState(false);
  const [openIdx, setOpenIdx] = React.useState(null);
  const visible = expanded ? items : items.slice(0, initialVisible);
  const hiddenCount = items.length - initialVisible;
  const open = openIdx != null ? items[openIdx] : null;
  const subs = open ? (SUBSPEC[open] || SUBSPEC_DEFAULT) : [];

  return (
    <div>
      <div className="spec-grid">
        {visible.map((s, i) => {
          const isOpen = openIdx === i;
          return (
            <div
              className="spec"
              key={i}
              role="button"
              tabIndex={0}
              onClick={() => setOpenIdx(isOpen ? null : i)}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpenIdx(isOpen ? null : i); } }}
              style={{
                background: isOpen ? 'var(--sky-tint)' : undefined,
                borderColor: isOpen ? 'var(--sky-deep)' : undefined,
              }}
            >
              <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
                <span>{s}</span>
                <span className="hand" style={{ fontSize: 14, color: 'var(--sky-deep)' }}>{isOpen ? '▾' : '▸'}</span>
              </span>
              {withCount && <span className="n">{12 + ((i * 17) % 80)} {t('specs_items')}</span>}
            </div>
          );
        })}
      </div>

      {open && (
        <div className="wf-border" style={{ marginTop: 14, padding: 16, background: 'var(--sky-tint)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 10, flexWrap: 'wrap' }}>
            <div>
              <div className="sec-tag" style={{ marginBottom: 4 }}>{t('subsubpec_tag')} · {open}</div>
              <div className="hand" style={{ fontSize: 22 }}>{t('refine_within')} {open}</div>
            </div>
            <button className="btn btn-ghost" onClick={() => setOpenIdx(null)}>✕ {t('close')}</button>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            <span className="chip chip-solid" onClick={() => goTo('catalogue')}>{t('all_of')} {open}</span>
            {subs.map((sub, j) => (
              <span key={j} className="chip" onClick={() => goTo('catalogue')} style={{ background: 'var(--paper)' }}>
                {sub}
                <span className="mono" style={{ marginLeft: 6, fontSize: 11, color: 'var(--muted)' }}>{4 + ((j * 13) % 40)}</span>
              </span>
            ))}
          </div>
          <div className="wf-rule-dash" style={{ margin: '12px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8, fontSize: 13, color: 'var(--ink-2)' }}>
            <span>{t('click_subspec')}</span>
            <a className="hand" style={{ fontSize: 17, color: 'var(--sky-deep)', cursor: 'pointer' }} onClick={() => goTo('catalogue')}>
              {t('enter_specialty')} {open} →
            </a>
          </div>
        </div>
      )}

      {hiddenCount > 0 && (
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 18 }}>
          <button className="btn" onClick={() => setExpanded(!expanded)}>
            {expanded ? `▴ ${t('specs_show_fewer')}` : `▾ ${t('specs_show_all')}`}
          </button>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CME tracker
// ─────────────────────────────────────────────────────────────
function CMETracker({ compact = false }) {
  const t = useT();
  if (compact) {
    return (
      <div className="wf-border" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div className="ring" data-pct="62%" />
        <div style={{ flex: 1, minWidth: 200 }}>
          <div className="hand" style={{ fontSize: 18 }}>{t('cme_compact_h')}</div>
          <div style={{ fontSize: 13, color: 'var(--muted)' }}>{t('cme_compact_s')}</div>
        </div>
        <button className="btn" onClick={() => goTo('dashboard')}>{t('cme_resume')}</button>
      </div>
    );
  }
  return (
    <div className="wf-border" style={{ padding: 20 }}>
      <div className="sec-tag" style={{ marginBottom: 10 }}>{t('cme_section_tag')}</div>
      <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' }}>
        <div className="ring" data-pct="62%" style={{ width: 80, height: 80 }} />
        <div style={{ flex: 1, minWidth: 220 }}>
          <div className="hand" style={{ fontSize: 22 }}>{t('cme_progress')}</div>
          <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{t('cme_cycle')}</div>
          <div className="wf-rule" style={{ marginTop: 8, marginBottom: 8 }} />
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', fontSize: 13 }}>
            <span className="chip chip-dash">{t('cme_in_progress')}</span>
            <span className="chip">{t('cme_up_next')}</span>
            <span className="chip">{t('cme_saved')}</span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <button className="btn btn-primary" onClick={() => goTo('article')}>{t('cme_resume')}</button>
          <button className="btn">{t('cme_transcript')}</button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Content card
// ─────────────────────────────────────────────────────────────
function ContentCard({ item, dense = false }) {
  const t = useT();
  return (
    <article
      className="card wf-border"
      style={{ padding: dense ? 12 : 16, cursor: 'pointer' }}
      onClick={() => goTo('article')}
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter') goTo('article'); }}
    >
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="stamp" style={item.kind === 'course' ? { background: 'var(--sky-tint)', color: 'var(--sky-deep)', borderColor: 'var(--sky-deep)' } : {}}>
          {item.kind === 'course' ? t('card_course') : t('card_article')}
        </span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{item.subj}</span>
      </header>
      <h3 className="hand" style={{ fontSize: dense ? 18 : 21, margin: 0, lineHeight: 1.2 }}>{item.title}</h3>
      <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.45, margin: 0 }}>{item.excerpt}</p>
      <div className="wf-rule-dash" />
      <footer style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13, color: 'var(--muted)' }}>
        <span className="mono">{item.time}{item.credits ? ` · ${item.credits}` : ''}</span>
        <span className="hand" style={{ fontSize: 17, color: 'var(--sky-deep)' }}>{t('card_open')}</span>
      </footer>
    </article>
  );
}

// ─────────────────────────────────────────────────────────────
// List row (catalogue list view)
// ─────────────────────────────────────────────────────────────
function ListRow({ item }) {
  return (
    <div
      onClick={() => goTo('article')}
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter') goTo('article'); }}
      style={{ display: 'flex', gap: 16, padding: '14px 0', borderBottom: '1px dashed var(--line)', cursor: 'pointer' }}
    >
      <div className="mono hide-mobile" style={{ width: 60, fontSize: 11, color: 'var(--muted)', paddingTop: 4 }}>
        {String(item.subj || '').slice(0, 8).toUpperCase()}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="hand" style={{ fontSize: 19, lineHeight: 1.2 }}>{item.title}</div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>{item.excerpt}</div>
        <div className="mono" style={{ display: 'flex', gap: 14, marginTop: 6, fontSize: 12, color: 'var(--muted)', flexWrap: 'wrap' }}>
          <span>{item.time}</span>
          {item.credits && <span>· {item.credits}</span>}
          <span>· {item.subj}</span>
        </div>
      </div>
      <div style={{ width: 30, display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
        <span className="hand" style={{ fontSize: 22, color: 'var(--sky-deep)' }}>→</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Subscription tiers
// ─────────────────────────────────────────────────────────────
function SubscriptionTiers() {
  const t = useT();
  const tiers = [
    { name: t('tier_reader'),       price: '₾0',         per: t('free_forever'), points: [t('tier_reader_p1'), t('tier_reader_p2'), t('tier_reader_p3')], cta: t('start_free'),  accent: false },
    { name: t('tier_practitioner'), price: '₾24',        per: t('per_month'),    points: [t('tier_pract_p1'), t('tier_pract_p2'), t('tier_pract_p3'), t('tier_pract_p4')], cta: t('start_trial'), accent: true, badge: t('most_popular') },
    { name: t('tier_institution'),  price: t('custom'),  per: t('per_seat'),     points: [t('tier_inst_p1'),  t('tier_inst_p2'),  t('tier_inst_p3'), t('tier_inst_p4')],   cta: t('talk_to_us'),  accent: false },
  ];
  return (
    <div className="tiers">
      {tiers.map((tier, i) => (
        <div key={i} className={'wf-border tier-card ' + (tier.accent ? 'is-accent' : '')}>
          {tier.badge && <span className="stamp stamp-ink badge">{tier.badge}</span>}
          <div className="sec-tag" style={{ marginBottom: 4 }}>{tier.name}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <div className="hand" style={{ fontSize: 38, lineHeight: 1 }}>{tier.price}</div>
            <div style={{ fontSize: 13, color: 'var(--muted)' }}>{tier.per}</div>
          </div>
          <div className="wf-rule" style={{ margin: '10px 0' }} />
          <ul className="tier-points">
            {tier.points.map((p, j) => (
              <li key={j}><span className="hand" style={{ color: 'var(--sky-deep)' }}>✓</span><span>{p}</span></li>
            ))}
          </ul>
          <button
            className={'btn btn-block ' + (tier.accent ? 'btn-primary' : '')}
            style={{ marginTop: 14 }}
            onClick={() => goTo('signup')}
          >
            {tier.cta}
          </button>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Newsletter
// ─────────────────────────────────────────────────────────────
function Newsletter() {
  const t = useT();
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (!email) return;
    setSent(true);
  };
  return (
    <div className="newsletter">
      <div>
        <div className="sec-tag" style={{ marginBottom: 4 }}>{t('newsletter_tag')}</div>
        <div className="hand" style={{ fontSize: 'clamp(22px, 2.6vw, 28px)', lineHeight: 1.1, marginBottom: 6 }}>
          <span className="scribble-under">{t('newsletter_title_a')}</span> {t('newsletter_title_b')}
        </div>
        <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{t('newsletter_sub')}</div>
      </div>
      <form onSubmit={submit}>
        <div className="search-input" style={{ padding: '8px 12px' }}>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder={t('email_placeholder')}
            aria-label={t('email_placeholder')}
            required
          />
          <button type="submit" className="btn btn-primary" style={{ padding: '8px 14px' }}>
            {sent ? '✓' : t('subscribe')}
          </button>
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>
          {sent ? 'Thanks — check your inbox.' : t('newsletter_foot')}
        </div>
      </form>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────────
function Footer() {
  const t = useT();
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="hand" style={{ fontSize: 24, marginBottom: 8 }}>OpenMedEdu</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', maxWidth: 280 }}>{t('footer_about')}</div>
          </div>
          <div className="foot-col">
            <strong>{t('foot_learn')}</strong>
            <a onClick={() => goTo('catalogue')}>{t('courses')}</a>
            <a onClick={() => goTo('catalogue')}>{t('articles')}</a>
            <a onClick={() => goTo('catalogue')}>{t('news')}</a>
            <a onClick={() => goTo('catalogue')}>{t('specs')}</a>
          </div>
          <div className="foot-col">
            <strong>{t('foot_for_you')}</strong>
            <a onClick={() => goTo('dashboard')}>{t('foot_cme')}</a>
            <a onClick={() => goTo('dashboard')}>{t('foot_bookmarks')}</a>
            <a onClick={() => goTo('dashboard')}>{t('foot_transcript')}</a>
            <a>{t('foot_mobile')}</a>
          </div>
          <div className="foot-col">
            <strong>{t('foot_company')}</strong>
            <a>{t('about')}</a>
            <a>{t('foot_editorial')}</a>
            <a>{t('foot_accred')}</a>
            <a>{t('foot_press')}</a>
          </div>
          <div className="foot-col">
            <strong>{t('foot_legal')}</strong>
            <a>{t('foot_terms')}</a>
            <a>{t('foot_privacy')}</a>
            <a>{t('foot_coi')}</a>
            <a>{t('foot_contact')}</a>
          </div>
        </div>
        <div className="wf-rule-dash" style={{ margin: '20px 0 12px' }} />
        <div className="foot-bottom mono">
          <span>{t('foot_copyright')}</span>
          <span>v 2026.05 · status · changelog</span>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────
// Section head helper
// ─────────────────────────────────────────────────────────────
function SectionHead({ tag, title, sub, action, onAction }) {
  return (
    <div className="section-head">
      <div>
        <div className="sec-tag">{tag}</div>
        <h2 className="hand h" style={{ margin: 0 }}>{title}</h2>
        {sub && <div className="s">{sub}</div>}
      </div>
      {action && (
        <a className="a" onClick={onAction}>{action}</a>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Catalogue tabs
// ─────────────────────────────────────────────────────────────
function CatalogueTabs({ active = 0, onChange }) {
  const t = useT();
  const tabs = [t('tab_all'), t('tab_courses'), t('tab_articles'), t('news'), t('tab_saved')];
  return (
    <div className="tabs" role="tablist">
      {tabs.map((label, i) => (
        <div
          key={i}
          role="tab"
          tabIndex={0}
          className={'tab ' + (i === active ? 'on' : '')}
          onClick={() => onChange && onChange(i)}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onChange && onChange(i); } }}
          aria-selected={i === active}
        >
          {label}
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Subject filter chip row (with state)
// ─────────────────────────────────────────────────────────────
function SubjectChipRow({ active = 0, onChange }) {
  const t = useT();
  const top = [
    t('subj_all'), t('subj_cardio'), t('subj_im'), t('subj_em'),
    t('subj_peds'), t('subj_psych'), t('subj_surg'), t('subj_onc'),
    t('subj_neuro'), t('subj_more'),
  ];
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {top.map((c, i) => (
        <span
          key={i}
          className={'chip ' + (i === active ? 'chip-solid' : '')}
          onClick={() => onChange && onChange(i)}
        >
          {c}
        </span>
      ))}
    </div>
  );
}

Object.assign(window, {
  NavBar, SpecialtyGrid, CMETracker, ContentCard, ListRow,
  SubscriptionTiers, Newsletter, Footer, SectionHead,
  CatalogueTabs, SubjectChipRow, goTo,
});
