// Directions pages: catalog + detail
const { useState: p3S, useMemo: p3M } = React;

// ============ DIRECTIONS CATALOG ============
const DirectionsCatalogPage = ({ onBook }) => {
  const [query, setQuery] = p3S('');

  const filtered = p3M(() => {
    if (!query.trim()) return DATA.directions;
    const q = query.toLowerCase();
    return DATA.directions.filter(d =>
      d.name.toLowerCase().includes(q) ||
      d.desc.toLowerCase().includes(q) ||
      (d.problems || []).some(p => p.toLowerCase().includes(q))
    );
  }, [query]);

  // Group directions into categories visually
  return (
    <>
      <PageHero
        eyebrow="Центры компетенций"
        title="Все направления"
        sub={`${DATA.directions.length} направлений медицины. От первичного приёма до сложной хирургии, диагностики и реабилитации — все экспертные службы НАЦЗДРАВ.`}
        breadcrumbs={[
          { label: 'Главная', href: 'index.html' },
          { label: 'Направления' },
        ]}
      />

      <section className="sec" style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="dn-search">
            <Icon name="search" size={18} className="dn-search__icon" />
            <input
              type="text"
              placeholder="Поиск по направлению, заболеванию..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            {query && (
              <button className="dn-search__clear" onClick={() => setQuery('')} aria-label="Очистить">
                <Icon name="close" size={14} />
              </button>
            )}
          </div>

          {filtered.length === 0 ? (
            <div className="dc-empty">
              <Icon name="search" size={36} />
              <h3>Ничего не найдено</h3>
              <p>Попробуйте сформулировать запрос иначе</p>
              <button className="btn btn-secondary" onClick={() => setQuery('')}>Сбросить</button>
            </div>
          ) : (
            <div className="dn-grid">
              {filtered.map((d) => {
                const doctorsCount = DATA.doctors.filter(doc => doc.directions && doc.directions.includes(d.id)).length;
                return (
                  <a key={d.id} href={`direction.html?id=${d.id}`} className="dn-card">
                    <div className="dn-card__top">
                      <div className="dn-card__icon">
                        <Icon name={d.icon} size={28} strokeWidth={1.4} />
                      </div>
                      <div className="dn-card__price">
                        <div className="dn-card__price-label">Приём от</div>
                        <div className="dn-card__price-value">{d.priceFrom}</div>
                      </div>
                    </div>
                    <h3 className="dn-card__title">{d.name}</h3>
                    <p className="dn-card__desc">{d.desc}</p>
                    <div className="dn-card__bottom">
                      <span className="dn-card__doctors">
                        <Icon name="doctor" size={14} />
                        {doctorsCount > 0 ? `${doctorsCount} ${pluralDoctors(doctorsCount)}` : 'команда центра'}
                      </span>
                      <span className="dn-card__more">
                        Перейти <Icon name="arrowR" size={14} />
                      </span>
                    </div>
                  </a>
                );
              })}
            </div>
          )}
        </div>

        <style>{`
          .dn-search {
            position: relative;
            display: flex;
            align-items: center;
            background: #fff;
            border: 1px solid var(--border-strong);
            border-radius: var(--r-sm);
            padding: 0 14px;
            margin-bottom: 28px;
            max-width: 560px;
          }
          .dn-search:focus-within { border-color: var(--navy-700); }
          .dn-search__icon { color: var(--ink-500); flex-shrink: 0; }
          .dn-search input {
            flex: 1;
            padding: 14px 12px;
            border: 0;
            background: transparent;
            font-size: 15px;
          }
          .dn-search input:focus { outline: none; }
          .dn-search__clear {
            width: 24px; height: 24px;
            border-radius: 999px;
            background: var(--navy-100);
            color: var(--ink-700);
            display: inline-flex;
            align-items: center;
            justify-content: center;
          }
          .dn-search__clear:hover { background: var(--navy-200); }

          .dn-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 14px;
          }
          @media (max-width: 960px) { .dn-grid { grid-template-columns: repeat(2, 1fr); } }
          @media (max-width: 540px) { .dn-grid { grid-template-columns: 1fr; } }

          .dn-card {
            display: flex;
            flex-direction: column;
            gap: 10px;
            padding: 28px 26px;
            background: #fff;
            border: 1px solid var(--border);
            border-radius: var(--r-md);
            transition: border-color .2s ease, box-shadow .2s ease, transform .2s ease;
          }
          .dn-card:hover {
            border-color: var(--navy-300);
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
          }
          .dn-card__top {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
          }
          .dn-card__icon {
            width: 56px; height: 56px;
            border-radius: var(--r-sm);
            background: var(--navy-100);
            color: var(--navy-700);
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background .2s ease, color .2s ease;
          }
          .dn-card:hover .dn-card__icon {
            background: var(--navy-800);
            color: #fff;
          }
          .dn-card__price { text-align: right; }
          .dn-card__price-label {
            font-size: 11px;
            color: var(--ink-500);
            text-transform: uppercase;
            letter-spacing: 0.06em;
          }
          .dn-card__price-value {
            font-size: 16px;
            font-weight: 600;
            color: var(--ink-900);
            margin-top: 2px;
          }
          .dn-card__title {
            font-size: 19px;
            font-weight: 600;
            color: var(--ink-900);
          }
          .dn-card__desc {
            font-size: 14px;
            color: var(--ink-500);
            line-height: 1.5;
            flex: 1;
          }
          .dn-card__bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 14px;
            margin-top: 6px;
            border-top: 1px solid var(--border);
            font-size: 13px;
          }
          .dn-card__doctors {
            color: var(--ink-700);
            display: inline-flex; align-items: center; gap: 6px;
          }
          .dn-card__doctors svg { color: var(--navy-600); }
          .dn-card__more {
            color: var(--navy-700);
            font-weight: 500;
            display: inline-flex; align-items: center; gap: 4px;
            transition: gap .2s ease;
          }
          .dn-card:hover .dn-card__more { gap: 8px; }
        `}</style>
      </section>
    </>
  );
};

function pluralDoctors(n) {
  const last = n % 10;
  const teens = n % 100;
  if (teens >= 11 && teens <= 14) return 'врачей';
  if (last === 1) return 'врач';
  if (last >= 2 && last <= 4) return 'врача';
  return 'врачей';
}

// ============ DIRECTION DETAIL ============
const DirectionDetailPage = ({ directionId, onBook }) => {
  const direction = p3M(() => DATA.directions.find(d => d.id === directionId), [directionId])
    || DATA.directions[0];

  const directionDoctors = p3M(() =>
    DATA.doctors.filter(doc => doc.directions && doc.directions.includes(direction.id))
  , [direction]);

  const [openFaq, setOpenFaq] = p3S(0);

  return (
    <>
      <section className="dt-hero">
        <div className="container">
          <Breadcrumbs items={[
            { label: 'Главная', href: 'index.html' },
            { label: 'Направления', href: 'directions.html' },
            { label: direction.name },
          ]} />

          <div className="dt-hero__inner">
            <div className="dt-hero__body">
              <div className="dt-hero__icon">
                <Icon name={direction.icon} size={32} strokeWidth={1.4} />
              </div>
              <span className="eyebrow">Центр компетенций</span>
              <h1 className="dt-name">{direction.name}</h1>
              <p className="dt-lead">{direction.longDesc}</p>

              <div className="dt-actions">
                <button className="btn btn-primary btn-lg" onClick={onBook}>
                  Записаться на приём
                </button>
                <a className="btn btn-secondary btn-lg" href="#problems">
                  Что мы лечим
                  <Icon name="arrowDown" size={16} />
                </a>
              </div>
            </div>

            <div className="dt-stats-card">
              <div className="dt-stat">
                <div className="dt-stat__label">Приём от</div>
                <div className="dt-stat__value">{direction.priceFrom}</div>
              </div>
              <div className="dt-stat">
                <div className="dt-stat__label">Врачей в направлении</div>
                <div className="dt-stat__value">{directionDoctors.length || '—'}</div>
              </div>
              <div className="dt-stat">
                <div className="dt-stat__label">Видов диагностики</div>
                <div className="dt-stat__value">{(direction.diagnostics || []).length}</div>
              </div>
              <div className="dt-stat">
                <div className="dt-stat__label">Методов лечения</div>
                <div className="dt-stat__value">{(direction.methods || []).length}</div>
              </div>
            </div>
          </div>
        </div>

        <style>{`
          .dt-hero { background: linear-gradient(180deg, var(--navy-50), #fff); padding-bottom: 48px; }
          .dt-hero__inner {
            display: grid;
            grid-template-columns: 1.5fr 1fr;
            gap: 56px;
            align-items: flex-start;
            padding-top: 8px;
          }
          .dt-hero__icon {
            width: 64px; height: 64px;
            border-radius: var(--r-md);
            background: var(--navy-800);
            color: #fff;
            display: flex; align-items: center; justify-content: center;
            margin-bottom: 18px;
          }
          .dt-name {
            font-size: clamp(36px, 5vw, 56px);
            line-height: 1.05;
            letter-spacing: -0.025em;
            margin-top: 8px;
          }
          .dt-lead {
            margin-top: 18px;
            font-size: 17px;
            color: var(--ink-700);
            line-height: 1.55;
          }
          .dt-actions {
            display: flex;
            gap: 10px;
            margin-top: 28px;
            flex-wrap: wrap;
          }
          .dt-stats-card {
            background: #fff;
            border: 1px solid var(--border);
            border-radius: var(--r-md);
            padding: 28px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
            box-shadow: var(--shadow-sm);
            position: sticky;
            top: 100px;
          }
          .dt-stat__label {
            font-size: 12px;
            color: var(--ink-500);
            text-transform: uppercase;
            letter-spacing: 0.06em;
          }
          .dt-stat__value {
            font-size: 28px;
            font-weight: 600;
            color: var(--ink-900);
            margin-top: 4px;
            letter-spacing: -0.02em;
          }

          @media (max-width: 960px) {
            .dt-hero__inner { grid-template-columns: 1fr; gap: 28px; }
            .dt-stats-card { position: static; }
          }
        `}</style>
      </section>

      {/* PROBLEMS */}
      <section id="problems" className="sec sec-soft">
        <div className="container">
          <SectionHead
            eyebrow="Кому подходит"
            title="С какими проблемами обращаются"
            sub="Если у вас есть один из этих симптомов или диагнозов — мы поможем разобраться и составить план лечения"
          />
          <div className="dt-problems">
            {(direction.problems || []).map((p, i) => (
              <div key={i} className="dt-prob">
                <span className="dt-prob__num">{String(i + 1).padStart(2, '0')}</span>
                <span className="dt-prob__text">{p}</span>
              </div>
            ))}
          </div>
        </div>
        <style>{`
          .dt-problems {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
          }
          @media (max-width: 740px) { .dt-problems { grid-template-columns: 1fr; } }
          .dt-prob {
            display: flex;
            gap: 14px;
            padding: 18px 22px;
            background: #fff;
            border: 1px solid var(--border);
            border-radius: var(--r-md);
            transition: border-color .2s ease;
          }
          .dt-prob:hover { border-color: var(--navy-300); }
          .dt-prob__num {
            font-family: var(--font-mono);
            font-size: 13px;
            color: var(--navy-600);
            font-weight: 500;
            flex-shrink: 0;
          }
          .dt-prob__text {
            font-size: 15px;
            color: var(--ink-900);
            line-height: 1.5;
          }
        `}</style>
      </section>

      {/* DIAGNOSTICS + METHODS */}
      <section className="sec">
        <div className="container">
          <div className="dt-cols">
            <div className="dt-col">
              <span className="eyebrow">Диагностика</span>
              <h2 style={{ marginTop: 10 }}>Что мы исследуем</h2>
              <p style={{ marginTop: 14, color: 'var(--ink-700)', fontSize: 16 }}>
                Современное оборудование экспертного класса и опытные диагносты. Все исследования сопровождаются расшифровкой.
              </p>
              <div className="dt-tags">
                {(direction.diagnostics || []).map((d, i) => (
                  <span key={i} className="dt-tag">
                    <Icon name="scan" size={14} />
                    {d}
                  </span>
                ))}
              </div>
            </div>

            <div className="dt-col">
              <span className="eyebrow">Лечение</span>
              <h2 style={{ marginTop: 10 }}>Методы лечения</h2>
              <p style={{ marginTop: 14, color: 'var(--ink-700)', fontSize: 16 }}>
                Подход всегда индивидуальный — мы подбираем терапию с учётом возраста, сопутствующих заболеваний и пожеланий пациента.
              </p>
              <div className="dt-tags">
                {(direction.methods || []).map((m, i) => (
                  <span key={i} className="dt-tag">
                    <Icon name="pill" size={14} />
                    {m}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
        <style>{`
          .dt-cols {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 48px;
          }
          @media (max-width: 880px) { .dt-cols { grid-template-columns: 1fr; gap: 32px; } }
          .dt-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 22px;
          }
          .dt-tag {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 14px;
            background: var(--navy-100);
            color: var(--navy-700);
            font-size: 13.5px;
            font-weight: 500;
            border-radius: var(--r-full);
          }
          .dt-tag svg { color: var(--navy-600); }
        `}</style>
      </section>

      {/* DOCTORS OF DIRECTION */}
      {directionDoctors.length > 0 && (
        <section className="sec sec-soft">
          <div className="container">
            <SectionHead
              eyebrow="Команда направления"
              title={`Врачи направления «${direction.name}»`}
              sub={`${directionDoctors.length} ${pluralDoctors(directionDoctors.length)} с опытом работы по этому профилю`}
              action={<a className="btn btn-secondary" href="doctors.html">Все врачи</a>}
            />
            <div className="dt-doctors">
              {directionDoctors.map(d => <DoctorCard key={d.id} doctor={d} onBook={onBook} />)}
            </div>
          </div>
          <style>{`
            .dt-doctors {
              display: grid;
              grid-template-columns: repeat(4, 1fr);
              gap: 16px;
            }
            @media (max-width: 1100px) { .dt-doctors { grid-template-columns: repeat(3, 1fr); } }
            @media (max-width: 820px) { .dt-doctors { grid-template-columns: repeat(2, 1fr); } }
            @media (max-width: 480px) { .dt-doctors { grid-template-columns: 1fr; } }
          `}</style>
        </section>
      )}

      {/* FAQ */}
      {direction.faq && direction.faq.length > 0 && (
        <section className="sec">
          <div className="container">
            <SectionHead
              eyebrow="Вопросы и ответы"
              title="FAQ по направлению"
            />
            <div className="dt-faq">
              {direction.faq.map((item, i) => (
                <div key={i} className={`dt-faq-item ${openFaq === i ? 'is-open' : ''}`}>
                  <button className="dt-faq-q" onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
                    <span>{item.q}</span>
                    <Icon name="chevD" size={20} className="dt-faq-icon" />
                  </button>
                  {openFaq === i && (
                    <div className="dt-faq-a">{item.a}</div>
                  )}
                </div>
              ))}
            </div>
          </div>
          <style>{`
            .dt-faq { display: flex; flex-direction: column; gap: 8px; }
            .dt-faq-item {
              background: #fff;
              border: 1px solid var(--border);
              border-radius: var(--r-md);
              overflow: hidden;
              transition: border-color .2s ease;
            }
            .dt-faq-item.is-open { border-color: var(--navy-300); box-shadow: var(--shadow-sm); }
            .dt-faq-q {
              width: 100%;
              padding: 18px 22px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              gap: 12px;
              font-size: 16px;
              font-weight: 500;
              color: var(--ink-900);
              text-align: left;
            }
            .dt-faq-q:hover { background: var(--navy-50); }
            .dt-faq-icon {
              color: var(--ink-500);
              transition: transform .2s ease;
              flex-shrink: 0;
            }
            .dt-faq-item.is-open .dt-faq-icon { transform: rotate(180deg); }
            .dt-faq-a {
              padding: 0 22px 22px;
              color: var(--ink-700);
              font-size: 15px;
              line-height: 1.6;
              animation: fadeUp .2s ease both;
            }
          `}</style>
        </section>
      )}

      {/* CTA */}
      <section className="sec">
        <div className="container">
          <div className="dt-cta">
            <div>
              <h2>Нужна помощь по направлению «{direction.name}»?</h2>
              <p>Запишитесь на консультацию или загрузите документы для консилиума.</p>
            </div>
            <div className="dt-cta__actions">
              <button className="btn btn-primary btn-lg" onClick={onBook}>Записаться</button>
              <a className="btn btn-secondary btn-lg" href="second-opinion.html">Второе мнение</a>
            </div>
          </div>
          <style>{`
            .dt-cta {
              padding: 40px 48px;
              background: var(--navy-800);
              color: #fff;
              border-radius: var(--r-lg);
              display: flex;
              align-items: center;
              justify-content: space-between;
              gap: 32px;
              flex-wrap: wrap;
            }
            .dt-cta h2 { color: #fff; }
            .dt-cta p { color: rgba(255,255,255,0.7); margin-top: 8px; font-size: 16px; }
            .dt-cta__actions { display: flex; gap: 10px; flex-wrap: wrap; }
            .dt-cta .btn-primary { background: var(--accent); }
            .dt-cta .btn-primary:hover { background: oklch(0.55 0.16 235); }
            .dt-cta .btn-secondary { background: transparent; color: #fff; border-color: rgba(255,255,255,0.2); }
            .dt-cta .btn-secondary:hover { border-color: #fff; background: rgba(255,255,255,0.06); }
            @media (max-width: 740px) { .dt-cta { padding: 28px; } }
          `}</style>
        </div>
      </section>
    </>
  );
};

Object.assign(window, { DirectionsCatalogPage, DirectionDetailPage, pluralDoctors });
