// components/shared.jsx
// Shared layout: Nav, Footer, PlaceholderImg, useReveal.
// Used by every page — pass `current` prop to Nav to highlight active item.
// `base` prop is the relative path prefix to the site root (e.g. '' on root pages, '../' on /hizmetler/*).

const { useState: useState_s, useEffect: useEffect_s } = React;

(function loadFontAwesomeOnce() {
  if (document.getElementById('tn-fa')) return;
  const l = document.createElement('link');
  l.id = 'tn-fa';
  l.rel = 'stylesheet';
  l.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css';
  document.head.appendChild(l);
})();

(function loadOpenSansOnce() {
  if (document.getElementById('tn-opensans')) return;
  const l = document.createElement('link');
  l.id = 'tn-opensans';
  l.rel = 'stylesheet';
  l.href = 'https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&display=swap';
  document.head.appendChild(l);
})();

/* ---------- scroll-reveal ---------- */
function useReveal() {
  useEffect_s(() => {
    // Fallback: if IntersectionObserver isn't available or doesn't fire, reveal everything after 600ms.
    const failsafe = setTimeout(() => {
      document.querySelectorAll('.reveal:not(.is-in)').forEach(el => el.classList.add('is-in'));
    }, 600);

    if (typeof IntersectionObserver === 'undefined') {
      return () => clearTimeout(failsafe);
    }

    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('is-in');
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal:not(.is-in)').forEach(el => obs.observe(el));
    return () => {
      clearTimeout(failsafe);
      obs.disconnect();
    };
  });
}

/* ---------- PlaceholderImg ---------- */
function PlaceholderImg({ label, variant = 'rose', seed = 0, tall = false }) {
  const palettes = {
    rose:     ['#fbe9e3', '#f5ccc0', '#eaa996'],
    nude:     ['#fbf4ed', '#e8d4c4', '#c2a085'],
    gold:     ['#f9e9cf', '#e5c99a', '#cfa866'],
    burgundy: ['#e8c4ba', '#c58a78', '#8a3c34'],
    berry:    ['#f5ccc0', '#e8b5c6', '#c5537a'],
    mocha:    ['#efe0d2', '#cdb29a', '#9d7b5f'],
    pearl:    ['#f9f3ee', '#e8dcd0', '#cdbfae'],
    milky:    ['#fff8f3', '#fce5d8', '#f5ccc0'],
  };
  const p = palettes[variant] || palettes.rose;
  const gid = `phg-${variant}-${seed}-${Math.random().toString(36).slice(2,7)}`;
  const sid = `phs-${variant}-${seed}-${Math.random().toString(36).slice(2,7)}`;
  return (
    <div className="ph" style={{ aspectRatio: tall ? '3/4' : '1/1' }}>
      <svg viewBox="0 0 400 400" preserveAspectRatio="xMidYMid slice" width="100%" height="100%">
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor={p[0]}/>
            <stop offset="0.55" stopColor={p[1]}/>
            <stop offset="1" stopColor={p[2]}/>
          </linearGradient>
          <radialGradient id={sid} cx="0.3" cy="0.25" r="0.6">
            <stop offset="0" stopColor="rgba(255,255,255,.55)"/>
            <stop offset="1" stopColor="rgba(255,255,255,0)"/>
          </radialGradient>
        </defs>
        <rect width="400" height="400" fill={`url(#${gid})`}/>
        <circle cx="80" cy="80" r="120" fill="#fff" opacity="0.12"/>
        <circle cx="340" cy="320" r="110" fill={p[2]} opacity="0.18"/>
        <rect width="400" height="400" fill={`url(#${sid})`}/>
        <path d="M-20 260 Q200 180 420 280 L420 420 L-20 420 Z" fill="#fff" opacity="0.15"/>
      </svg>
      <div className="ph__label">
        <small>Görsel</small>
        <b>{label}</b>
      </div>
    </div>
  );
}

/* ---------- SERVICES NAV DATA ---------- */
const SERVICE_PAGES = [
  { slug: 'tirnak-bakim',   t: 'Tırnak Bakım Uygulamaları' },
  { slug: 'incelme',        t: 'Bölgesel İncelme' },
  { slug: 'cilt',           t: 'Cilt Bakımı Uygulamaları' },
  { slug: 'epilasyon',      t: 'Lazer Epilasyon Uygulaması' },
  { slug: 'masaj',          t: 'Masaj Hizmetleri' },
  { slug: 'kalici-makyaj',  t: 'Kalıcı Makyaj Uygulamaları' },
  { slug: 'kirpik-kas',     t: 'Kirpik - Kaş Uygulamaları' },
];

/* ---------- Nav ----------
   current: 'home' | 'hizmetler' | 'hakkimizda' | 'galeri' | 'iletisim' | <service-slug>
   base:    relative prefix to site root, e.g. '' or '../'
*/
function Nav({ current = 'home', base = '' }) {
  const [scrolled, setScrolled] = useState_s(false);
  const [open, setOpen] = useState_s(false);
  const [svcOpen, setSvcOpen] = useState_s(false);
  useEffect_s(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const href = (path) => base + path;
  const links = [
    { key: 'hakkimizda', h: href('hakkimizda.html'), t: 'Hakkımızda' },
    { key: 'galeri',     h: href('galeri.html'),     t: 'Galeri' },
    { key: 'iletisim',   h: href('iletisim.html'),   t: 'İletişim' },
  ];
  const isServiceCurrent = SERVICE_PAGES.some(s => s.slug === current) || current === 'hizmetler';

  return (
    <>
      <nav className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
        <div className="wrap nav__inner">
          <a href={href('index.html')} className="brand">
            <img src={href('assets/tulinail_logo.png')} alt="TüliNail Beauty Club" className="brand__logo"/>
          </a>
          <ul className="nav__links">
            <li><a href={href('index.html')} className={current === 'home' ? 'is-active' : ''}>Ana Sayfa</a></li>
            <li className="has-sub"
                onMouseEnter={() => setSvcOpen(true)}
                onMouseLeave={() => setSvcOpen(false)}>
              <a href={href('hizmetler.html')} className={isServiceCurrent ? 'is-active' : ''}>
                Hizmetler <span style={{fontSize:9, marginLeft:4}}>▼</span>
              </a>
              <div className={`submenu ${svcOpen ? 'is-open' : ''}`}>
                {SERVICE_PAGES.map(s => (
                  <a key={s.slug} href={href('hizmetler/' + s.slug + '.html')} className={current === s.slug ? 'is-active' : ''}>{s.t}</a>
                ))}
              </div>
            </li>
            {links.map(l => (
              <li key={l.key}><a href={l.h} className={current === l.key ? 'is-active' : ''}>{l.t}</a></li>
            ))}
          </ul>
          <a href={href('iletisim.html#randevu')} className="btn btn--primary nav__cta">
            Randevu Al <span className="arr">→</span>
          </a>
          <button className={`nav__burger ${open ? 'is-open' : ''}`} onClick={() => setOpen(o => !o)} aria-label="Menu">
            <span></span><span></span><span></span>
          </button>
        </div>
      </nav>

      <div className={`mobile-menu ${open ? 'is-open' : ''}`}>
        <a href={href('index.html')}>Ana Sayfa</a>
        {SERVICE_PAGES.map(s => (
          <a key={s.slug} href={href('hizmetler/' + s.slug + '.html')} style={{fontSize:18, opacity:.82}}>{s.t}</a>
        ))}
        <a href={href('hakkimizda.html')}>Hakkımızda</a>
        <a href={href('galeri.html')}>Galeri</a>
        <a href={href('iletisim.html')}>İletişim</a>
        <a href={href('iletisim.html#randevu')} className="btn btn--primary">Randevu Al</a>
      </div>
    </>
  );
}

/* ---------- Footer ---------- */
function Footer({ base = '' }) {
  const href = (p) => base + p;
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer__grid">
          <div>
            <div className="brand">
              <img src={href('assets/tulinail_logo.png')} alt="TüliNail Beauty Club" className="brand__logo brand__logo--footer"/>
            </div>
            <p style={{marginTop:18}}>Güzellik merkezi<br/>Etiler / Beşiktaş / İstanbul.</p>
            <div className="footer__social">
              <a href="https://www.instagram.com/tulinailbeautyclub" target="_blank" rel="noopener" aria-label="Instagram"><i className="fa-brands fa-instagram"></i></a>
              <a href="https://wa.me/905453452431?text=Merhaba" target="_blank" rel="noopener" aria-label="WhatsApp"><i className="fa-brands fa-whatsapp"></i></a>
            </div>
          </div>
          <div>
            <h4>Hizmetler</h4>
            <ul>
              {SERVICE_PAGES.map(s => (
                <li key={s.slug}><a href={href('hizmetler/' + s.slug + '.html')}>{s.t}</a></li>
              ))}
              <li><a href={href('hizmetler.html')} style={{color:'var(--rose-500)'}}>Tümünü Gör →</a></li>
            </ul>
          </div>
          <div>
            <h4>Keşfet</h4>
            <ul>
              <li><a href={href('hakkimizda.html')}>Hakkımızda</a></li>
              <li><a href={href('galeri.html')}>Galeri</a></li>
              <li><a href={href('iletisim.html')}>İletişim</a></li>
              <li><a href={href('iletisim.html#randevu')}>Randevu Al</a></li>
            </ul>
          </div>
          <div>
            <h4>İletişim</h4>
            <ul>
              <li>Kültür Mah. Suna Sk.</li>
              <li>No: 76 · Etiler / Beşiktaş / İstanbul</li>
              <li>Nail: +90 545 345 24 31</li>
              <li>Beauty: +90 506 198 27 31</li>
              <li>Salı – Pazar · 10:00 – 19:00</li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <span>© 2026 TüliNail Beauty Club. Tüm hakları saklıdır.</span>
          <span>Gizlilik · KVKK · Çerezler</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Accent color applier (reads ?accent=rose|berry|nude|burgundy from URL, persists in localStorage) ---------- */
const ACCENT_PALETTES = {
  rose:     { '--rose-400':'#d98b76', '--rose-500':'#c06b55', '--rose-600':'#9a4d3c', '--gold-500':'#b08842' },
  berry:    { '--rose-400':'#c5537a', '--rose-500':'#a33a62', '--rose-600':'#7c2944', '--gold-500':'#cfa866' },
  nude:     { '--rose-400':'#c2a085', '--rose-500':'#9d7b5f', '--rose-600':'#6e5339', '--gold-500':'#b08842' },
  burgundy: { '--rose-400':'#8a3c34', '--rose-500':'#6a2620', '--rose-600':'#4a1612', '--gold-500':'#cfa866' },
};
function applyAccent(name) {
  const palette = ACCENT_PALETTES[name] || ACCENT_PALETTES.rose;
  const root = document.documentElement;
  Object.entries(palette).forEach(([k, v]) => root.style.setProperty(k, v));
}

/* ---------- Page header (for inner pages) ---------- */
function PageHead({ eyebrow, title, subtitle, variant = 'rose', bgImage = null }) {
  const hasPhoto = !!bgImage;
  return (
    <section className={`page-head page-head--${variant}${hasPhoto ? ' page-head--photo' : ''}`}>
      {hasPhoto && <div className="page-head__photo" style={{ backgroundImage: `url('${bgImage}')` }} aria-hidden="true"></div>}
      <div className="wrap">
        <div className="page-head__inner reveal">
          {eyebrow && <span className="eyebrow center">{eyebrow}</span>}
          <h1>{title}</h1>
          {subtitle && <p>{subtitle}</p>}
        </div>
      </div>
      <div className="page-head__deco" aria-hidden="true"></div>
    </section>
  );
}

/* ---------- expose globally ---------- */
Object.assign(window, {
  useReveal, PlaceholderImg, Nav, Footer, PageHead,
  SERVICE_PAGES, ACCENT_PALETTES, applyAccent,
});
