// Page-level components: DoctorsCatalogPage, DoctorDetailPage
const { useState: pS, useMemo: pM, useEffect: pE } = React;

// ============ BREADCRUMBS ============
const Breadcrumbs = ({ items }) => (
  <nav className="crumbs">
    {items.map((it, i) => (
      <React.Fragment key={i}>
        {i > 0 && <span className="crumbs__sep">/</span>}
        {it.href
          ? <a href={it.href} className="crumbs__link">{it.label}</a>
          : <span className="crumbs__current">{it.label}</span>}
      </React.Fragment>
    ))}
    <style>{`
      .crumbs {
        display: flex; align-items: center; gap: 8px;
        font-size: 13px; color: var(--ink-500);
        padding: 16px 0;
        flex-wrap: wrap;
      }
      .crumbs__sep { color: var(--ink-300); }
      .crumbs__link { color: var(--ink-500); transition: color .15s ease; }
      .crumbs__link:hover { color: var(--navy-700); }
      .crumbs__current { color: var(--ink-900); }
    `}</style>
  </nav>
);

// ============ PAGE HERO ============
const PageHero = ({ eyebrow, title, sub, breadcrumbs, action }) => (
  <section className="page-hero">
    <div className="container">
      {breadcrumbs && <Breadcrumbs items={breadcrumbs} />}
      <div className="page-hero__inner">
        <div>
          {eyebrow && <span className="eyebrow">{eyebrow}</span>}
          <h1 className="page-hero__title">{title}</h1>
          {sub && <p className="page-hero__sub">{sub}</p>}
        </div>
        {action && <div>{action}</div>}
      </div>
    </div>
    <style>{`
      .page-hero {
        background: linear-gradient(180deg, var(--navy-50), #fff);
        padding-bottom: 36px;
      }
      .page-hero__inner {
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        gap: 32px;
        flex-wrap: wrap;
        padding: 8px 0 24px;
      }
      .page-hero__title {
        margin-top: 12px;
        font-size: clamp(34px, 4.5vw, 52px);
        letter-spacing: -0.03em;
        font-weight: 600;
        line-height: 1.05;
        max-width: 760px;
      }
      .page-hero__sub {
        margin-top: 14px;
        font-size: 17px;
        color: var(--ink-700);
        max-width: 620px;
        line-height: 1.5;
      }
    `}</style>
  </section>
);

// ============ DOCTORS CATALOG ============
const DoctorsCatalogPage = ({ onBook }) => {
  const [query, setQuery] = pS('');
  const [selectedDirs, setSelectedDirs] = pS([]);
  const [degreeOnly, setDegreeOnly] = pS(false);
  const [minExp, setMinExp] = pS(0);
  const [sort, setSort] = pS('exp-desc');

  const toggleDir = (id) => {
    setSelectedDirs((cur) =>
      cur.includes(id) ? cur.filter(x => x !== id) : [...cur, id]
    );
  };

  const filtered = pM(() => {
    let arr = DATA.doctors.slice();
    if (query.trim()) {
      const q = query.toLowerCase();
      arr = arr.filter(d =>
        d.fullName.toLowerCase().includes(q) ||
        d.specs.some(s => s.toLowerCase().includes(q)) ||
        d.tags.some(t => t.toLowerCase().includes(q))
      );
    }
    if (selectedDirs.length) {
      arr = arr.filter(d => d.directions && d.directions.some(x => selectedDirs.includes(x)));
    }
    if (degreeOnly) {
      arr = arr.filter(d => d.degree);
    }
    if (minExp > 0) {
      arr = arr.filter(d => parseInt(d.experience) >= minExp);
    }
    if (sort === 'exp-desc') arr.sort((a, b) => parseInt(b.experience) - parseInt(a.experience));
    if (sort === 'exp-asc')  arr.sort((a, b) => parseInt(a.experience) - parseInt(b.experience));
    if (sort === 'name')     arr.sort((a, b) => a.fullName.localeCompare(b.fullName, 'ru'));
    return arr;
  }, [query, selectedDirs, degreeOnly, minExp, sort]);

  const reset = () => {
    setQuery(''); setSelectedDirs([]); setDegreeOnly(false); setMinExp(0);
  };

  return (
    <>
      <PageHero
        eyebrow="Команда центра"
        title="Врачи НАЦЗДРАВ"
        sub={`${DATA.doctors.length} специалистов с опытом работы в федеральных центрах и научными степенями. Найдите врача по направлению или имени.`}
        breadcrumbs={[
          { label: 'Главная', href: 'index.html' },
          { label: 'Врачи' },
        ]}
      />

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

            <div className="dc-sort">
              <label>Сортировка:</label>
              <select value={sort} onChange={(e) => setSort(e.target.value)}>
                <option value="exp-desc">По опыту (по убыванию)</option>
                <option value="exp-asc">По опыту (по возрастанию)</option>
                <option value="name">По алфавиту</option>
              </select>
            </div>
          </div>

          {/* Direction chips */}
          <div className="dc-chips">
            <span className="dc-chips__label">Направление:</span>
            {DATA.directions.map((d) => (
              <button
                key={d.id}
                className={`dc-chip ${selectedDirs.includes(d.id) ? 'is-active' : ''}`}
                onClick={() => toggleDir(d.id)}
              >
                <Icon name={d.icon} size={14} />
                {d.name}
              </button>
            ))}
            {(selectedDirs.length > 0 || query || degreeOnly || minExp > 0) && (
              <button className="dc-chip dc-chip--reset" onClick={reset}>
                <Icon name="close" size={12} />
                Сбросить
              </button>
            )}
          </div>

          {/* Quick options */}
          <div className="dc-quick">
            <label className="dc-quick__toggle">
              <input type="checkbox" checked={degreeOnly} onChange={(e) => setDegreeOnly(e.target.checked)} />
              <span className="dc-quick__box"></span>
              Только с учёной степенью
            </label>

            <div className="dc-quick__exp">
              <label>Стаж от:</label>
              {[0, 5, 10, 15, 20].map((y) => (
                <button
                  key={y}
                  className={`dc-quick__pill ${minExp === y ? 'is-active' : ''}`}
                  onClick={() => setMinExp(y)}
                >{y === 0 ? 'любой' : `${y}+ лет`}</button>
              ))}
            </div>

            <div className="dc-quick__count">
              Найдено: <strong>{filtered.length}</strong> из {DATA.doctors.length}
            </div>
          </div>

          {/* Results */}
          {filtered.length === 0 ? (
            DATA.doctors.length === 0 ? (
              <div className="dc-empty">
                <Icon name="doctor" size={36} />
                <h3>Список врачей пока пуст</h3>
                <p>Скоро здесь появятся специалисты центра</p>
                <button className="btn btn-primary" onClick={onBook}>Записаться на приём</button>
              </div>
            ) : (
              <div className="dc-empty">
                <Icon name="search" size={36} />
                <h3>Ничего не найдено</h3>
                <p>Попробуйте сбросить фильтры или изменить запрос</p>
                <button className="btn btn-secondary" onClick={reset}>Сбросить фильтры</button>
              </div>
            )
          ) : (
            <div className="dc-grid">
              {filtered.map((doc) => (
                <DoctorCard key={doc.id} doctor={doc} onBook={onBook} />
              ))}
            </div>
          )}
        </div>

        <style>{`
          .dc-filters {
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 16px;
            margin-bottom: 18px;
            align-items: center;
          }
          .dc-search {
            position: relative;
            display: flex;
            align-items: center;
            background: #fff;
            border: 1px solid var(--border-strong);
            border-radius: var(--r-sm);
            padding: 0 14px;
          }
          .dc-search:focus-within { border-color: var(--navy-700); }
          .dc-search__icon { color: var(--ink-500); flex-shrink: 0; }
          .dc-search input {
            flex: 1;
            padding: 14px 12px;
            border: 0;
            background: transparent;
            font-size: 15px;
          }
          .dc-search input:focus { outline: none; }
          .dc-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;
          }
          .dc-search__clear:hover { background: var(--navy-200); }

          .dc-sort {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: var(--ink-700);
          }
          .dc-sort select {
            padding: 10px 14px;
            border-radius: var(--r-sm);
            border: 1px solid var(--border-strong);
            background: #fff;
            font-size: 14px;
            cursor: pointer;
          }

          .dc-chips {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
            margin-bottom: 14px;
          }
          .dc-chips__label {
            font-size: 13px;
            color: var(--ink-500);
            margin-right: 4px;
          }
          .dc-chip {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 7px 12px;
            border-radius: var(--r-full);
            background: #fff;
            border: 1px solid var(--border-strong);
            color: var(--ink-700);
            font-size: 13px;
            font-weight: 500;
            transition: border-color .15s ease, background .15s ease, color .15s ease;
          }
          .dc-chip:hover { border-color: var(--navy-700); color: var(--ink-900); }
          .dc-chip.is-active {
            background: var(--navy-800);
            border-color: var(--navy-800);
            color: #fff;
          }
          .dc-chip.is-active svg { color: #fff; }
          .dc-chip svg { color: var(--navy-600); }
          .dc-chip--reset {
            border-color: var(--danger);
            color: var(--danger);
          }
          .dc-chip--reset:hover { background: oklch(0.60 0.18 25 / 0.08); color: var(--danger); }

          .dc-quick {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 24px;
            margin-bottom: 28px;
            padding: 16px 20px;
            background: var(--navy-50);
            border-radius: var(--r-md);
            border: 1px solid var(--border);
          }
          .dc-quick__toggle {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: var(--ink-700);
            cursor: pointer;
          }
          .dc-quick__toggle input { display: none; }
          .dc-quick__box {
            width: 18px; height: 18px;
            border-radius: 4px;
            border: 1.5px solid var(--border-strong);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: background .15s ease, border-color .15s ease;
          }
          .dc-quick__toggle input:checked + .dc-quick__box {
            background: var(--navy-800);
            border-color: var(--navy-800);
          }
          .dc-quick__toggle input:checked + .dc-quick__box::after {
            content: "";
            width: 5px; height: 9px;
            border-right: 2px solid #fff;
            border-bottom: 2px solid #fff;
            transform: rotate(45deg) translate(-1px, -1px);
          }
          .dc-quick__exp {
            display: flex; align-items: center; gap: 6px;
            font-size: 14px; color: var(--ink-700);
          }
          .dc-quick__exp label { color: var(--ink-700); }
          .dc-quick__pill {
            padding: 5px 12px;
            border-radius: var(--r-full);
            border: 1px solid transparent;
            background: #fff;
            color: var(--ink-700);
            font-size: 13px;
            font-weight: 500;
            transition: background .15s ease, color .15s ease;
          }
          .dc-quick__pill:hover { background: var(--navy-100); }
          .dc-quick__pill.is-active {
            background: var(--navy-800);
            color: #fff;
          }
          .dc-quick__count {
            margin-left: auto;
            font-size: 13.5px;
            color: var(--ink-500);
          }
          .dc-quick__count strong { color: var(--ink-900); }

          .dc-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 16px;
          }
          @media (max-width: 1100px) { .dc-grid { grid-template-columns: repeat(3, 1fr); } }
          @media (max-width: 820px) { .dc-grid { grid-template-columns: repeat(2, 1fr); } }
          @media (max-width: 480px) { .dc-grid { grid-template-columns: 1fr; } }

          .dc-empty {
            padding: 64px 24px;
            text-align: center;
            background: var(--navy-50);
            border-radius: var(--r-lg);
            border: 1px dashed var(--border-strong);
          }
          .dc-empty svg { color: var(--ink-400); }
          .dc-empty h3 { margin: 14px 0 6px; }
          .dc-empty p { color: var(--ink-500); margin-bottom: 16px; }

          @media (max-width: 760px) {
            .dc-filters { grid-template-columns: 1fr; }
            .dc-quick { gap: 14px; }
            .dc-quick__count { margin-left: 0; }
          }
        `}</style>
      </section>
    </>
  );
};

// ============ DOCTOR CARD (catalog version) ============
const DoctorCard = ({ doctor, onBook }) => {
  return (
    <article className="dcard">
      <a className="dcard__link" href={`doctor.html?id=${doctor.id}`}>
        <div className="dcard__photo">
          {doctor.photo
            ? <img src={doctor.photo} alt={doctor.fullName} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'var(--r-md) var(--r-md) 0 0' }} />
            : <ImagePlaceholder
                label={doctor.photoLabel}
                style={{ height: '100%', borderRadius: 'var(--r-md) var(--r-md) 0 0' }}
              />}
          {doctor.degree && <span className="dcard__degree">{doctor.degree}</span>}
        </div>
        <div className="dcard__body">
          <h3 className="dcard__name">{doctor.fullName}</h3>
          <div className="dcard__specs">{doctor.specs.join(', ')}</div>
          <div className="dcard__meta">
            <span><Icon name="award" size={14} /> Стаж {doctor.experience}</span>
            <span>{doctor.price}</span>
          </div>
        </div>
      </a>
      <div className="dcard__actions">
        <button className="btn btn-primary btn-sm" onClick={(e) => { e.stopPropagation(); onBook(); }}>
          Записаться
        </button>
        <a className="btn btn-secondary btn-sm" href={`doctor.html?id=${doctor.id}`}>
          Подробнее
        </a>
      </div>
      <style>{`
        .dcard {
          background: #fff;
          border: 1px solid var(--border);
          border-radius: var(--r-md);
          overflow: hidden;
          display: flex;
          flex-direction: column;
          transition: border-color .2s ease, box-shadow .2s ease, transform .2s ease;
        }
        .dcard:hover {
          border-color: var(--border-strong);
          box-shadow: var(--shadow-md);
          transform: translateY(-2px);
        }
        .dcard__link {
          display: flex;
          flex-direction: column;
          flex: 1;
          color: inherit;
        }
        .dcard__photo {
          aspect-ratio: 4/4.4;
          position: relative;
        }
        .dcard__degree {
          position: absolute;
          top: 12px; left: 12px;
          padding: 4px 10px;
          background: var(--navy-800);
          color: #fff;
          font-size: 11px;
          font-weight: 500;
          border-radius: var(--r-full);
          letter-spacing: 0.04em;
          text-transform: uppercase;
        }
        .dcard__body { padding: 16px 18px 0; display: flex; flex-direction: column; gap: 6px; flex: 1; }
        .dcard__name { font-size: 16.5px; font-weight: 600; color: var(--ink-900); }
        .dcard__specs { font-size: 13.5px; color: var(--ink-500); line-height: 1.4; flex: 1; }
        .dcard__meta {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 8px;
          font-size: 12.5px;
          color: var(--ink-700);
          padding: 10px 0 0;
        }
        .dcard__meta span { display: inline-flex; align-items: center; gap: 5px; }
        .dcard__meta svg { color: var(--navy-600); }
        .dcard__actions {
          display: flex;
          gap: 6px;
          padding: 14px 18px 18px;
        }
        .dcard__actions .btn { flex: 1; }
      `}</style>
    </article>
  );
};

Object.assign(window, { DoctorsCatalogPage, DoctorCard, Breadcrumbs, PageHero });
