const { useState, useEffect } = React;

// ── Icons (filled / duotone style — different from previous outline set) ──
const Ico = ({ n, s = 24 }) => {
  const d = {
    bus: <><rect x="2" y="5" width="20" height="15" rx="3" fill="currentColor" opacity=".2"/><path d="M2 10h20M7 15h.01M17 15h.01M2 8a3 3 0 013-3h14a3 3 0 013 3v9a2 2 0 01-2 2H4a2 2 0 01-2-2V8z" stroke="currentColor" strokeWidth="1.75" fill="none"/><path d="M6 20v1M18 20v1" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></>,
    plane: <><path d="M21 16v-2l-8-5V3.5a1.5 1.5 0 00-3 0V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5L21 16z" fill="currentColor" opacity=".85"/></>,
    truck: <><path d="M1 3h15v13H1z" fill="currentColor" opacity=".2"/><path d="M1 3h15v13H1zM16 8h4l3 4v4h-7" stroke="currentColor" strokeWidth="1.75" fill="none" strokeLinejoin="round"/><circle cx="5.5" cy="18.5" r="2.5" fill="currentColor"/><circle cx="18.5" cy="18.5" r="2.5" fill="currentColor"/></>,
    globe: <><circle cx="12" cy="12" r="10" fill="currentColor" opacity=".15"/><circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.75" fill="none"/><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10A15.3 15.3 0 0112 2z" stroke="currentColor" strokeWidth="1.75" fill="none"/><line x1="2" y1="12" x2="22" y2="12" stroke="currentColor" strokeWidth="1.75"/></>,
    shield: <><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" fill="currentColor" opacity=".2"/><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke="currentColor" strokeWidth="1.75" fill="none"/><polyline points="9 12 11 14 15 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" fill="none"/></>,
    wrench: <><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" fill="currentColor" opacity=".2" stroke="currentColor" strokeWidth="1.75" fill="none"/></>,
    heart: <><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" fill="currentColor" opacity=".85"/></>,
    medkit: <><rect x="2" y="7" width="20" height="14" rx="3" fill="currentColor" opacity=".2"/><path d="M2 10a3 3 0 013-3h14a3 3 0 013 3v8a3 3 0 01-3 3H5a3 3 0 01-3-3v-8zM8 3h8M12 12v4M10 14h4" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" fill="none"/></>,
    award: <><circle cx="12" cy="9" r="6" fill="currentColor" opacity=".2"/><circle cx="12" cy="9" r="6" stroke="currentColor" strokeWidth="1.75" fill="none"/><path d="M8.21 13.89L7 23l5-3 5 3-1.21-9.12" stroke="currentColor" strokeWidth="1.75" fill="none"/><path d="M12 6v3M10.5 7.5L12 9l1.5-1.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" fill="none"/></>,
    check: <><polyline points="20 6 9 17 4 12" stroke="currentColor" strokeWidth="2.5" fill="none" strokeLinecap="round"/></>,
    chevron: <><polyline points="6 9 12 15 18 9" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round"/></>,
    phone: <><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.81a2 2 0 012-2.18h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L9.09 15.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z" fill="currentColor" opacity=".85"/></>,
    mail: <><path d="M4 4h16a2 2 0 012 2v12a2 2 0 01-2 2H4a2 2 0 01-2-2V6a2 2 0 012-2z" fill="currentColor" opacity=".2" stroke="currentColor" strokeWidth="1.75" fill="none"/><polyline points="22 6 12 13 2 6" stroke="currentColor" strokeWidth="1.75" fill="none"/></>,
    pin: <><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z" fill="currentColor" opacity=".2" stroke="currentColor" strokeWidth="1.75" fill="none"/><circle cx="12" cy="10" r="3" fill="currentColor"/></>,
    arrow: <><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><polyline points="12 5 19 12 12 19" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round"/></>,
    send: <><polygon points="22 2 11 13" fill="currentColor" opacity=".2"/><polygon points="22 2 15 22 11 13 2 9 22 2" stroke="currentColor" strokeWidth="1.75" fill="none" strokeLinejoin="round"/></>,
    fb: <><path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z" fill="currentColor"/></>,
    ig: <><rect x="2" y="2" width="20" height="20" rx="5" stroke="currentColor" strokeWidth="1.75" fill="none"/><path d="M16 11.37A4 4 0 1112.63 8 4 4 0 0116 11.37z" stroke="currentColor" strokeWidth="1.75" fill="none"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></>,
    li: <><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6z" fill="currentColor"/><rect x="2" y="9" width="4" height="12" fill="currentColor"/><circle cx="4" cy="4" r="2" fill="currentColor"/></>,
    up: <><polyline points="18 15 12 9 6 15" stroke="currentColor" strokeWidth="2.5" fill="none" strokeLinecap="round"/></>,
    users: <><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="1.75" fill="none"/><circle cx="9" cy="7" r="4" fill="currentColor" opacity=".25" stroke="currentColor" strokeWidth="1.75"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="currentColor" strokeWidth="1.75" fill="none"/></>,
    book: <><path d="M4 19.5A2.5 2.5 0 016.5 17H20" stroke="currentColor" strokeWidth="1.75" fill="none"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z" fill="currentColor" opacity=".2" stroke="currentColor" strokeWidth="1.75" fill="none"/></>,
    clock: <><circle cx="12" cy="12" r="10" fill="currentColor" opacity=".15" stroke="currentColor" strokeWidth="1.75"/><polyline points="12 6 12 12 16 14" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" fill="none"/></>,
    tg: <><path d="M22 3L2 11l6 2 2 7 4-4 6 5z" fill="currentColor"/></>,
    wa: <><path d="M20 4a10 10 0 00-16 12L2 22l6-2a10 10 0 0012-16zM8.5 8c.3 0 .6 0 .8.5l1 2c0 .3 0 .5-.2.7l-.5.6c.6 1.2 1.5 2.1 2.7 2.7l.6-.5c.2-.2.4-.2.7-.2l2 1c.5.2.5.5.5.8 0 1.2-1 2.4-2 2.4-3 0-7-3.4-7-7 0-1 1.2-2 2.4-2z" fill="currentColor"/></>,
    vb: <><path d="M11 1c5 0 9 4 9 9v1l-3-1-2 4-2-1-1 2-3-1 1-3-2-1-1-3 4-2-1-3 1-1zm0 2v2a7 7 0 017 7h2a9 9 0 00-9-9zm0 3v2a4 4 0 014 4h2a6 6 0 00-6-6z" fill="currentColor"/></>,
  };
  return (
    <svg viewBox="0 0 24 24" style={{ width: s, height: s, display: 'block' }} xmlns="http://www.w3.org/2000/svg">
      {d[n] || d.award}
    </svg>
  );
};

// ── Header ────────────────────────────────────────────────
const Header = ({ navigate, currentPage }) => {
  const [sc, setSc] = useState(false);
  const [open, setOpen] = useState(false);
  const c = window.CONTENT || {};
  const hData = c.header || {};
  useEffect(() => {
    const h = () => setSc(window.scrollY > 20);
    window.addEventListener('scroll', h);
    return () => window.removeEventListener('scroll', h);
  }, []);
  useEffect(() => { setOpen(false); }, [currentPage]);

  const links = (hData.navLinks && hData.navLinks.length)
    ? hData.navLinks.map(i => [i.path, i.label])
    : [['/', 'Головна'], ['/about', 'Про нас'], ['/services', 'Послуги'], ['/documents', 'Документи'], ['/contact', 'Контакти']];
  const isOn = p => p === '/' ? (currentPage === '/' || currentPage === '') : currentPage.startsWith(p);

  return (
    <>
      <header id="hdr" className={sc ? 'scrolled' : ''}>
        <div className="wrap">
          <div className="hdr-inner">
            <div className="hdr-logo" onClick={() => navigate('/')}>
              <img src={hData.logoImage || 'uploads/logo.png'} alt="ЦРТК Логотип" />
              <div className="hdr-name">
                <strong>{hData.logoTitle || 'Центр Розвитку'}</strong>
                <span>{hData.logoSubtitle || 'Проф. Компетентностей'}</span>
              </div>
            </div>
            <nav style={{ marginLeft: 32 }}>
              <ul className="hdr-nav">
                {links.map(([p, l]) => (
                  <li key={p}>
                    <a href={`#${p}`} className={isOn(p) ? 'on' : ''}
                      onClick={e => { e.preventDefault(); navigate(p); }}>{l}</a>
                  </li>
                ))}
              </ul>
            </nav>
            <div className="hdr-right">
              <a href={hData.phoneHref || 'tel:+380672641041'} className="hdr-phone">{hData.phone || '+38 (067) 264-10-41'}</a>
              <button className="btn btn-blue btn-sm" onClick={() => navigate('/contact')}>{hData.ctaButton || 'Записатися'}</button>
              <button className="burger" onClick={() => setOpen(o => !o)} aria-label="Меню">
                {open
                  ? <><span style={{ transform: 'translateY(7px) rotate(45deg)' }}></span><span style={{ opacity: 0 }}></span><span style={{ transform: 'translateY(-7px) rotate(-45deg)' }}></span></>
                  : <><span></span><span></span><span></span></>}
              </button>
            </div>
          </div>
        </div>
      </header>
      <div className={`mob-nav ${open ? 'open' : ''}`}>
        {links.map(([p, l]) => (
          <a key={p} href={`#${p}`}
            onClick={e => { e.preventDefault(); navigate(p); setOpen(false); }}>{l}</a>
        ))}
        <button className="btn btn-blue" onClick={() => { navigate('/contact'); setOpen(false); }}>
          {hData.ctaButton || 'Записатися на курс'}
        </button>
      </div>
    </>
  );
};

// ── Footer ────────────────────────────────────────────────
const Footer = ({ navigate }) => {
  const c = window.CONTENT || {};
  const f = c.footer || {};
  const courses = (window.CONTENT?.services || []).map(s => [s.slug, s.title]);
  const navLinks = (c.header && c.header.navLinks && c.header.navLinks.length)
    ? c.header.navLinks
    : [
      { path: '/', label: 'Головна' },
      { path: '/about', label: 'Про нас' },
      { path: '/services', label: 'Послуги' },
      { path: '/documents', label: 'Документи' },
      { path: '/contact', label: 'Контакти' },
    ];
  const partnerLinks = f.partnerLinks || [];
  return (
    <footer>
      <div className="wrap">
        <div className="ft-grid">
          <div className="ft-col">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, cursor: 'pointer' }}
              onClick={() => navigate('/')}>
              <img src={c.header?.logoImage || 'uploads/logo.png'} alt="logo" style={{ height: 38, width: 'auto' }} />
              <div>
                <div style={{ fontFamily: "'Outfit',sans-serif", fontWeight: 800, fontSize: 14, color: '#fff', lineHeight: 1.2 }}>{c.header?.logoTitle || 'Центр Розвитку'}</div>
                <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 10, fontWeight: 600, color: 'rgba(255,255,255,0.4)', textTransform: 'uppercase', letterSpacing: '1.5px' }}>{c.header?.logoSubtitle || 'Професійних Компетентностей'}</div>
              </div>
            </div>
            <p>{f.description || 'ТОВ «Центр Розвитку Професійних Компетентностей» — офіційний навчальний центр у сфері транспорту, безпеки та медичного забезпечення дорожнього руху.'}</p>
            <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
              {[['fb', '#'], ['ig', '#']].map(([ic, hr]) => (
                <a key={ic} href={hr} className="soc-btn"><Ico n={ic} s={32} /></a>
              ))}
            </div>
          </div>
          {/* <div className="ft-col">
            <h5>{f.navTitle || 'Навігація'}</h5>
            {navLinks.map(item => (
              <a key={item.path} href={`#${item.path}`} onClick={e => { e.preventDefault(); navigate(item.path); }}>{item.label}</a>
            ))}
          </div> */}
          <div className="ft-col" style={{ gridColumn: 'span 2' }}>
            <h5>{f.coursesTitle || 'Програми'}</h5>
            <div className="ft-col-programs-grid">
              {courses.map(([s, l]) => (
                <a key={s} href={`#/service/${s}`}
                  onClick={e => { e.preventDefault(); navigate(`/service/${s}`); }}>{l}</a>
              ))}
            </div>
          </div>
          <div className="ft-col">
            <h5>{f.contactsTitle || 'Контакти'}</h5>
            <p><strong style={{ color: 'rgba(255,255,255,0.6)' }}>Телефон:</strong><br />{f.phone || '+38 (067) 264-10-41'}</p>
            <p style={{ marginTop: 8 }}><strong style={{ color: 'rgba(255,255,255,0.6)' }}>Email:</strong><br />{f.email || 'cdpc.tov@gmail.com'}</p>
            <p style={{ marginTop: 8 }}><strong style={{ color: 'rgba(255,255,255,0.6)' }}>Графік:</strong><br />{f.address || 'Пн–Пт: 09:00–18:00'}</p>
          </div>
        </div>
        <div className="ft-bot">
          <span>{f.copyright || `© ${new Date().getFullYear()} ТОВ «ЦРПК». Усі права захищено.`}</span>
          <div className="ft-partners">
            {partnerLinks.map((item, i) => (
              <a key={i} href={item.href || '#'}>{item.label || ''}</a>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
};

// ── Course start date — reads from window.COURSE_START_DATES ──
const CourseStartDate = ({ slug, variant = 'pill', size = 'md', label = 'Найближчий старт' }) => {
  const dateStr = window.formatCourseDate(slug, { withYear: false });
  if (variant === 'inline') {
    return (
      <span>
        <span style={{ color: 'rgba(255,255,255,0.55)' }}>{label}: </span>
        <span className="start-date-inline">{dateStr}</span>
      </span>
    );
  }
  if (variant === 'block') {
    return (
      <div>
        <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)', marginBottom: 6 }}>{label}</div>
        <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 22, fontWeight: 800, color: '#86efac' }}>{dateStr}</div>
      </div>
    );
  }
  return (
    <span className={`start-date-pill ${size === 'lg' ? 'lg' : ''}`}>
      <span className="dot"></span>
      {label}: {dateStr}
    </span>
  );
};

Object.assign(window, { Ico, Header, Footer, CourseStartDate });
