// Page sections for НАЦЗДРАВ
const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM } = React;

// ============ HERO ============
const Hero = ({ onBook, onSecondOpinion }) => {
  return (
    <section id="home" className="hero">
      <div className="container hero__inner">
        <div className="hero__copy">
          <span className="eyebrow">Центр сложных клинических случаев</span>
          <h1 className="hero__headline">
            {DATA.hero.headline.map((line, i) => (
              <span key={i} className="hero__line" style={{ animationDelay: `${i * 0.08}s` }}>{line}</span>
            ))}
          </h1>
          <p className="hero__sub">{DATA.hero.sub}</p>

          <div className="hero__ctas">
            <button className="btn btn-primary btn-lg" onClick={onSecondOpinion}>
              Получить второе мнение
              <Icon name="arrow" size={18} />
            </button>
            <button className="btn btn-secondary btn-lg" onClick={onBook}>
              Записаться на приём
            </button>
          </div>

          <div className="hero__badges">
            {DATA.hero.badges.map((b, i) => (
              <div key={i} className="hero-badge">
                <Icon name="check" size={16} className="hero-badge__icon" />
                <div>
                  <div className="hero-badge__title">{b.title}</div>
                  <div className="hero-badge__note">{b.note}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="hero__visual">
          <div className="hero__photo">
            <img src="assets/clinic-front.jpg" alt="Фасад здания НАЦЗДРАВ" className="hero__img" />
          </div>
        </div>
      </div>

      <style>{`
        .hero {
          background:
            radial-gradient(1200px 600px at 100% 30%, oklch(0.94 0.025 245), transparent 60%),
            linear-gradient(180deg, var(--navy-50), #fff);
          padding: 56px 0 64px;
          overflow: hidden;
          position: relative;
        }
        .hero__inner {
          display: grid;
          grid-template-columns: 1fr 1.2fr;
          gap: 32px;
          align-items: center;
          position: relative;
          z-index: 2;
        }
        .hero__headline {
          margin: 18px 0 22px;
        }
        .hero__line {
          display: block;
          opacity: 1;
          transform: translateY(0);
          animation: heroLine .7s cubic-bezier(.22,.61,.36,1) backwards;
        }
        @keyframes heroLine {
          from { opacity: 0; transform: translateY(12px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @media (prefers-reduced-motion: reduce) {
          .hero__line { animation: none; }
        }
        .hero__sub {
          font-size: 18px;
          color: var(--ink-700);
          max-width: 480px;
          line-height: 1.5;
        }
        .hero__ctas {
          display: flex;
          gap: 12px;
          flex-wrap: wrap;
          margin: 32px 0 36px;
        }
        .hero__badges {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 16px;
          max-width: 600px;
        }
        .hero-badge {
          display: flex; gap: 10px; align-items: flex-start;
        }
        .hero-badge__icon {
          color: var(--navy-700);
          flex-shrink: 0;
          margin-top: 4px;
          padding: 3px;
          background: var(--navy-100);
          border-radius: 999px;
          width: 22px;
          height: 22px;
        }
        .hero-badge__title { font-size: 14px; font-weight: 600; color: var(--ink-900); line-height: 1.25; }
        .hero-badge__note { font-size: 13px; color: var(--ink-500); line-height: 1.35; margin-top: 2px; }

        .hero__visual {
          position: relative;
          height: 520px;
        }
        .hero__photo {
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          height: 90%;
          aspect-ratio: 1086 / 796;
        }
        .hero__img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          object-position: center center;
          display: block;
          /* Soft fade on all edges so photo melts into background */
          -webkit-mask-image:
            linear-gradient(to right,  transparent 0%, #000 22%, #000 90%, transparent 100%),
            linear-gradient(to bottom, transparent 0%, #000 8%, #000 78%, transparent 100%);
          -webkit-mask-composite: source-in;
                  mask-image:
            linear-gradient(to right,  transparent 0%, #000 22%, #000 90%, transparent 100%),
            linear-gradient(to bottom, transparent 0%, #000 8%, #000 78%, transparent 100%);
                  mask-composite: intersect;
        }
        @media (max-width: 960px) {
          .hero__visual { height: auto; }
          .hero__photo {
            position: relative;
            transform: none;
            top: 0; right: 0;
            height: auto;
            width: 100%;
          }
        }
        .hero__photo-overlay {
          position: absolute; inset: 0;
          pointer-events: none;
        }
        .hero-tag {
          position: absolute;
          background: rgba(255,255,255,0.95);
          backdrop-filter: blur(8px);
          border: 1px solid var(--border);
          border-radius: var(--r-md);
          padding: 12px 14px;
          display: flex;
          align-items: center;
          gap: 10px;
          box-shadow: var(--shadow-md);
          min-width: 160px;
        }
        .hero-tag--main {
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          background: var(--navy-800);
          border-color: var(--navy-800);
          padding: 16px 20px;
        }
        .hero-tag__dot {
          width: 8px; height: 8px;
          border-radius: 999px;
          background: var(--accent);
          box-shadow: 0 0 0 4px oklch(0.62 0.16 235 / 0.18);
          flex-shrink: 0;
        }
        .hero-tag__title { font-size: 13px; font-weight: 600; color: var(--ink-900); line-height: 1.2; }
        .hero-tag__sub { font-size: 11px; color: var(--ink-500); margin-top: 2px; }

        @media (max-width: 960px) {
          .hero__inner { grid-template-columns: 1fr; gap: 32px; }
          .hero__badges { grid-template-columns: 1fr; }
        }
      `}</style>
    </section>
  );
};

// ============ QUICK SEARCH (with autocomplete) ============
const QuickSearch = () => {
  const [active, setActive] = useS(null); // 'service' | 'direction' | 'doctor' | null
  const [query, setQuery] = useS('');
  const [selection, setSelection] = useS({ service: '', direction: '', doctor: '' });

  const ref = useR(null);

  useE(() => {
    const onClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setActive(null);
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  const options = useM(() => {
    if (active === 'service') return DATA.services;
    if (active === 'direction') return DATA.directions.map(d => d.name);
    if (active === 'doctor') return DATA.doctors.map(d => `${d.fullName} — ${d.specs[0]}`);
    return [];
  }, [active]);

  const filtered = useM(() => {
    if (!query.trim()) return options.slice(0, 8);
    const q = query.toLowerCase();
    return options.filter(o => o.toLowerCase().includes(q)).slice(0, 8);
  }, [options, query]);

  const fields = [
    { key: 'service',   label: 'Услуга',       placeholder: 'Найти услугу',     icon: 'pill' },
    { key: 'direction', label: 'Направление',  placeholder: 'Выбрать направление', icon: 'stethoscope' },
    { key: 'doctor',    label: 'Врач',         placeholder: 'Найти врача',      icon: 'doctor' },
  ];

  const handlePick = (val) => {
    setSelection({ ...selection, [active]: val });
    setActive(null);
    setQuery('');
  };

  return (
    <section id="search" className="qsearch">
      <div className="container">
        <div className="qsearch__card" ref={ref}>
          <div className="qsearch__label">
            <Icon name="search" size={16} />
            <span>Быстрый поиск</span>
          </div>

          {fields.map((f) => (
            <div key={f.key} className={`qs-field ${active === f.key ? 'is-active' : ''}`}>
              <Icon name={f.icon} size={20} className="qs-field__icon" />
              <div className="qs-field__body">
                <div className="qs-field__label">{f.label}</div>
                <input
                  id={f.key === 'service' ? 'quick-search-input' : undefined}
                  className="qs-field__input"
                  placeholder={f.placeholder}
                  value={active === f.key ? query : selection[f.key]}
                  onFocus={() => { setActive(f.key); setQuery(selection[f.key] || ''); }}
                  onChange={(e) => setQuery(e.target.value)}
                />
              </div>
              <Icon name="chevD" size={16} className="qs-field__chev" />

              {active === f.key && (
                <div className="qs-dropdown">
                  {filtered.length === 0 && (
                    <div className="qs-empty">Ничего не найдено</div>
                  )}
                  {filtered.map((opt) => (
                    <button key={opt} className="qs-option" onMouseDown={() => handlePick(opt)}>
                      <Icon name={f.icon} size={16} className="qs-option__icon" />
                      <span>{opt}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}

          <button className="qsearch__btn" aria-label="Найти" onClick={() => {/* search */}}>
            <Icon name="search" size={20} />
          </button>
        </div>
      </div>

      <style>{`
        .qsearch {
          position: relative;
          margin-top: -32px;
          z-index: 5;
          padding-bottom: 28px;
        }
        .qsearch__card {
          display: grid;
          grid-template-columns: auto 1fr 1fr 1fr auto;
          gap: 0;
          align-items: stretch;
          background: #fff;
          border-radius: var(--r-md);
          box-shadow: var(--shadow-lg);
          padding: 14px;
          border: 1px solid var(--border);
        }
        .qsearch__label {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 0 22px 0 14px;
          border-right: 1px solid var(--border);
          font-weight: 500;
          font-size: 14px;
          color: var(--ink-700);
          margin-right: 8px;
        }
        .qs-field {
          position: relative;
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 6px 18px;
          border-radius: var(--r-sm);
          cursor: text;
          transition: background .15s ease;
        }
        .qs-field + .qs-field {
          border-left: 1px solid var(--border);
        }
        .qs-field:hover { background: var(--navy-50); }
        .qs-field.is-active { background: var(--navy-50); }
        .qs-field__icon { color: var(--navy-700); flex-shrink: 0; }
        .qs-field__body { flex: 1; min-width: 0; }
        .qs-field__label {
          font-size: 12px;
          color: var(--ink-700);
          font-weight: 500;
          line-height: 1.2;
        }
        .qs-field__input {
          width: 100%;
          border: 0;
          background: transparent;
          padding: 0;
          font-size: 14px;
          color: var(--ink-900);
          margin-top: 2px;
        }
        .qs-field__input:focus { outline: none; }
        .qs-field__input::placeholder { color: var(--ink-400); }
        .qs-field__chev { color: var(--ink-400); flex-shrink: 0; }
        .qs-field.is-active .qs-field__chev { transform: rotate(180deg); }

        .qs-dropdown {
          position: absolute;
          top: calc(100% + 8px);
          left: 0; right: 0;
          background: #fff;
          border: 1px solid var(--border);
          border-radius: var(--r-md);
          box-shadow: var(--shadow-md);
          padding: 6px;
          z-index: 20;
          max-height: 320px;
          overflow-y: auto;
          animation: fadeUp .15s ease both;
        }
        .qs-option {
          display: flex;
          align-items: center;
          gap: 10px;
          width: 100%;
          padding: 10px 12px;
          border-radius: var(--r-sm);
          font-size: 14px;
          text-align: left;
          color: var(--ink-900);
        }
        .qs-option:hover { background: var(--navy-50); }
        .qs-option__icon { color: var(--navy-600); flex-shrink: 0; }
        .qs-empty {
          padding: 14px;
          color: var(--ink-500);
          font-size: 14px;
          text-align: center;
        }

        .qsearch__btn {
          width: 64px;
          background: var(--navy-800);
          color: #fff;
          border-radius: var(--r-sm);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 8px;
          transition: background .15s ease;
        }
        .qsearch__btn:hover { background: var(--navy-700); }

        @media (max-width: 960px) {
          .qsearch__card { grid-template-columns: 1fr; }
          .qsearch__label { border-right: 0; border-bottom: 1px solid var(--border); padding-bottom: 10px; margin: 0 0 8px 0; }
          .qs-field + .qs-field { border-left: 0; border-top: 1px solid var(--border); }
          .qsearch__btn { width: 100%; height: 48px; margin: 8px 0 0 0; }
        }
      `}</style>
    </section>
  );
};

// ============ DIRECTIONS (Centers of competence) ============
const Directions = ({ onBook }) => {
  return (
    <section id="directions" className="sec sec-soft">
      <div className="container">
        <SectionHead
          eyebrow="Направления"
          title="Наши центры компетенций"
          sub="20+ направлений медицины — от первичного приёма до сложной хирургии и реабилитации"
          action={
            <a className="btn btn-secondary" href="directions.html">
              Все направления
              <Icon name="arrow" size={16} />
            </a>
          }
        />

        <div className="dir-grid">
          {DATA.directions.slice(0, 12).map((d) => (
            <a key={d.id} href={`direction.html?id=${d.id}`} className="dir-card">
              <div className="dir-card__icon">
                <Icon name={d.icon} size={28} strokeWidth={1.4} />
              </div>
              <h3 className="dir-card__title">{d.name}</h3>
              <p className="dir-card__desc">{d.desc}</p>
              <span className="dir-card__more">
                Подробнее
                <Icon name="arrowR" size={14} />
              </span>
            </a>
          ))}
        </div>
      </div>

      <style>{`
        .dir-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 12px;
        }
        .dir-card {
          background: #fff;
          border: 1px solid var(--border);
          border-radius: var(--r-md);
          padding: 24px 22px 22px;
          display: flex;
          flex-direction: column;
          gap: 10px;
          transition: border-color .2s ease, box-shadow .2s ease, transform .2s ease;
          position: relative;
        }
        .dir-card:hover {
          border-color: var(--navy-300);
          box-shadow: var(--shadow-md);
          transform: translateY(-2px);
        }
        .dir-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;
          margin-bottom: 4px;
          transition: background .2s ease, color .2s ease;
        }
        .dir-card:hover .dir-card__icon {
          background: var(--navy-800);
          color: #fff;
        }
        .dir-card__title {
          font-size: 18px;
          font-weight: 600;
          color: var(--ink-900);
        }
        .dir-card__desc {
          font-size: 13.5px;
          color: var(--ink-500);
          line-height: 1.5;
          flex: 1;
        }
        .dir-card__more {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          color: var(--navy-700);
          font-weight: 500;
          margin-top: 6px;
          opacity: 0;
          transform: translateY(4px);
          transition: opacity .2s ease, transform .2s ease;
        }
        .dir-card:hover .dir-card__more { opacity: 1; transform: translateY(0); }

        @media (max-width: 1100px) { .dir-grid { grid-template-columns: repeat(3, 1fr); } }
        @media (max-width: 740px)  { .dir-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 440px)  { .dir-grid { grid-template-columns: 1fr; } }
      `}</style>
    </section>
  );
};

// ============ DOCTORS ============
const Doctors = ({ onBook }) => {
  const scrollerRef = useR(null);

  const scroll = (dir) => {
    const el = scrollerRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * 360, behavior: 'smooth' });
  };

  // Если врачей ещё нет — секцию на главной не показываем
  if (!DATA.doctors || DATA.doctors.length === 0) return null;

  return (
    <section id="doctors" className="sec">
      <div className="container">
        <SectionHead
          eyebrow="Команда"
          title="Наши эксперты"
          sub="Врачи с большим опытом, практикой в федеральных центрах и научными степенями"
          action={
            <div className="doctors__actions">
              <button className="btn-arrow" onClick={() => scroll(-1)} aria-label="Назад"><Icon name="arrowL" size={18} /></button>
              <button className="btn-arrow" onClick={() => scroll(1)}  aria-label="Вперёд"><Icon name="arrowR" size={18} /></button>
              <a className="btn btn-secondary" href="doctors.html">Все врачи</a>
            </div>
          }
        />

        <div className="doctors-scroll" ref={scrollerRef}>
          {DATA.doctors.map((doc) => (
            <article key={doc.id} className="doc-card">
              <a className="doc-card__photo" href={`doctor.html?id=${doc.id}`}>
                {doc.photo
                  ? <img src={doc.photo} alt={doc.fullName} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'var(--r-md) var(--r-md) 0 0' }} />
                  : <ImagePlaceholder
                      label={doc.photoLabel}
                      style={{ height: '100%', borderRadius: 'var(--r-md) var(--r-md) 0 0' }}
                    />}
                {doc.degree && <span className="doc-card__degree">{doc.degree}</span>}
              </a>
              <div className="doc-card__body">
                <a className="doc-card__name-link" href={`doctor.html?id=${doc.id}`}>
                  <h3 className="doc-card__name">{doc.fullName}</h3>
                </a>
                <div className="doc-card__specs">{doc.specs.join(', ')}</div>
                <div className="doc-card__meta">
                  <span className="doc-card__exp">Стаж {doc.experience}</span>
                  <span className="doc-card__sep" />
                  {doc.tags.slice(0, 1).map(t => <span key={t} className="doc-card__tag">{t}</span>)}
                </div>
                <button className="btn btn-secondary btn-sm doc-card__btn" onClick={onBook}>
                  Записаться
                </button>
              </div>
            </article>
          ))}
        </div>
      </div>

      <style>{`
        .doctors__actions { display: flex; gap: 8px; align-items: center; }
        .btn-arrow {
          width: 42px; height: 42px;
          border-radius: var(--r-sm);
          border: 1px solid var(--border-strong);
          background: #fff;
          color: var(--navy-800);
          display: inline-flex;
          align-items: center; justify-content: center;
          transition: border-color .15s ease, background .15s ease;
        }
        .btn-arrow:hover { border-color: var(--navy-800); background: var(--navy-50); }

        .doctors-scroll {
          display: grid;
          grid-auto-flow: column;
          grid-auto-columns: minmax(240px, 1fr);
          gap: 14px;
          overflow-x: auto;
          scroll-snap-type: x mandatory;
          padding-bottom: 8px;
          margin: 0 calc(var(--gutter) * -1);
          padding-left: var(--gutter);
          padding-right: var(--gutter);
        }
        .doctors-scroll::-webkit-scrollbar { height: 6px; }
        .doc-card {
          background: #fff;
          border: 1px solid var(--border);
          border-radius: var(--r-md);
          overflow: hidden;
          transition: border-color .2s ease, box-shadow .2s ease;
          scroll-snap-align: start;
          display: flex; flex-direction: column;
        }
        .doc-card:hover {
          border-color: var(--border-strong);
          box-shadow: var(--shadow-md);
        }
        .doc-card__photo {
          aspect-ratio: 4/4.6;
          background: var(--navy-100);
          position: relative;
        }
        .doc-card__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;
        }
        .doc-card__body { padding: 16px 18px 18px; display: flex; flex-direction: column; gap: 6px; flex: 1; }
        .doc-card__name { font-size: 16.5px; font-weight: 600; color: var(--ink-900); }
        .doc-card__specs { font-size: 13.5px; color: var(--ink-500); line-height: 1.4; flex: 1; }
        .doc-card__meta {
          display: flex; align-items: center; gap: 8px;
          margin-top: 4px;
          font-size: 12.5px;
          color: var(--ink-700);
        }
        .doc-card__sep { width: 3px; height: 3px; border-radius: 999px; background: var(--ink-300); }
        .doc-card__tag {
          padding: 3px 8px;
          background: var(--navy-100);
          color: var(--navy-700);
          border-radius: var(--r-full);
          font-size: 11.5px;
        }
        .doc-card__btn { margin-top: 12px; align-self: flex-start; }
      `}</style>
    </section>
  );
};

Object.assign(window, { Hero, QuickSearch, Directions, Doctors });
