/* ============================================================
   AURELIA RESIDENCES — Shared Layout (Nav, Footer, Hooks, Loader)
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;

/* ---------- HOOKS ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('[data-reveal], .split-text');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('is-visible');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function useScrolled(threshold = 60) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [threshold]);
  return scrolled;
}

function useCursor() {
  useEffect(() => {
    if (window.matchMedia('(pointer: coarse)').matches) return;
    const dot = document.createElement('div');
    dot.className = 'custom-cursor';
    const ring = document.createElement('div');
    ring.className = 'custom-cursor-ring';
    document.body.append(dot, ring);

    let mx = 0, my = 0, rx = 0, ry = 0;
    const onMove = (e) => { mx = e.clientX; my = e.clientY;
      dot.style.left = mx + 'px'; dot.style.top = my + 'px';
    };
    const tick = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      ring.style.left = rx + 'px';
      ring.style.top = ry + 'px';
      requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    requestAnimationFrame(tick);

    const setHover = (on) => {
      dot.classList.toggle('is-hover', on);
      ring.style.opacity = on ? '0' : '0.5';
    };
    document.querySelectorAll('a, button, [data-cursor-hover]').forEach(el => {
      el.addEventListener('mouseenter', () => setHover(true));
      el.addEventListener('mouseleave', () => setHover(false));
    });

    // re-bind on dynamic content
    const mo = new MutationObserver(() => {
      document.querySelectorAll('a, button, [data-cursor-hover]').forEach(el => {
        if (el.dataset.cursorBound) return;
        el.dataset.cursorBound = '1';
        el.addEventListener('mouseenter', () => setHover(true));
        el.addEventListener('mouseleave', () => setHover(false));
      });
    });
    mo.observe(document.body, { childList: true, subtree: true });

    return () => {
      mo.disconnect();
      window.removeEventListener('mousemove', onMove);
      dot.remove(); ring.remove();
    };
  }, []);
}

function useLoader() {
  const [done, setDone] = useState(false);
  useEffect(() => {
    if (sessionStorage.getItem('aurelia_loaded')) { setDone(true); return; }
    const t = setTimeout(() => {
      sessionStorage.setItem('aurelia_loaded', '1');
      setDone(true);
    }, 2600);
    return () => clearTimeout(t);
  }, []);
  return done;
}

function useCounter(target, opts = {}) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      if (!entries[0].isIntersecting) return;
      const start = performance.now();
      const dur = opts.duration || 1800;
      const step = (now) => {
        const t = Math.min(1, (now - start) / dur);
        const eased = 1 - Math.pow(1 - t, 4);
        setVal(eased * target);
        if (t < 1) requestAnimationFrame(step);
        else setVal(target);
      };
      requestAnimationFrame(step);
      io.disconnect();
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [target]);
  return [ref, val];
}

function useMagnetic() {
  useEffect(() => {
    const handler = (el) => {
      const onMove = (e) => {
        const r = el.getBoundingClientRect();
        const dx = e.clientX - (r.left + r.width / 2);
        const dy = e.clientY - (r.top + r.height / 2);
        el.style.transform = `translate(${dx * 0.18}px, ${dy * 0.22}px)`;
      };
      const onLeave = () => { el.style.transform = ''; };
      el.addEventListener('mousemove', onMove);
      el.addEventListener('mouseleave', onLeave);
    };
    document.querySelectorAll('[data-magnetic]').forEach(handler);
  }, []);
}

/* ---------- LOADER ---------- */
function Loader() {
  const done = useLoader();
  return (
    <div className={`loader ${done ? 'is-done' : ''}`}>
      <svg viewBox="0 0 88 110">
        {/* Building line drawing */}
        <path className="loader-line" d="M 8 100 L 8 30 L 44 8 L 80 30 L 80 100 Z M 24 100 L 24 50 L 44 50 L 44 100 M 50 50 L 70 50 L 70 100 M 24 70 L 44 70 M 50 70 L 70 70" />
      </svg>
      <div className="loader-brand">AURELIA</div>
    </div>
  );
}

/* ---------- MOBILE MENU (Aurelia) ---------- */
function AureliaMobileMenu({ active, links, onIndex }) {
  const [open, setOpen] = useState(false);
  useEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
      window.addEventListener('keydown', onKey);
      return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
    }
  }, [open]);
  return (
    <Fragment>
      <button
        className={`aurelia-mm-btn ${open ? 'is-open' : ''}`}
        aria-label={open ? 'Затвори меню' : 'Отвори меню'}
        aria-expanded={open}
        aria-controls="aurelia-mm-panel"
        onClick={() => setOpen(o => !o)}
      >
        <span></span><span></span><span></span>
      </button>
      <div
        id="aurelia-mm-panel"
        className={`aurelia-mm ${open ? 'is-open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-hidden={!open}
      >
        <div className="aurelia-mm-backdrop" onClick={() => setOpen(false)}></div>
        <div className="aurelia-mm-panel">
          <div className="aurelia-mm-head">
            <span className="aurelia-mm-brand">AURELIA<small>Residences · Sofia</small></span>
            <button className="aurelia-mm-close" aria-label="Затвори меню" onClick={() => setOpen(false)}>×</button>
          </div>
          <nav className="aurelia-mm-nav">
            {links.map((l, i) => (
              <a
                key={l.id}
                href={l.href}
                className={`aurelia-mm-link ${active === l.id ? 'active' : ''}`}
                style={{ transitionDelay: `${0.05 + i * 0.04}s` }}
                onClick={() => setOpen(false)}
              >
                <span className="aurelia-mm-num">0{i + 1}</span>
                <span>{l.label}</span>
              </a>
            ))}
          </nav>
          <div className="aurelia-mm-foot">
            <div className="lang-switch">
              <button className="active">BG</button><span>·</span>
              <button>EN</button><span>·</span>
              <button>DE</button>
            </div>
            <a href={onIndex ? 'booking/booking.html' : '../booking/booking.html'} className="aurelia-mm-cta">Резервирайте оглед →</a>
          </div>
        </div>
      </div>
    </Fragment>
  );
}

/* ---------- NAV ---------- */
function Nav({ active = 'home', dark = true }) {
  const scrolled = useScrolled(40);
  const links = [
    { id: 'home', label: 'Начало', href: '../index.html' },
    { id: 'projects', label: 'Проекти', href: '../projects/projects.html' },
    { id: 'locations', label: 'Локации', href: '../locations/locations.html' },
    { id: 'investment', label: 'Инвестиции', href: '../investment/investment.html' },
    { id: 'about', label: 'За нас', href: '../about/about.html' },
    { id: 'process', label: 'Процес', href: '../process/process.html' },
    { id: 'contact', label: 'Контакти', href: '../contact/contact.html' },
  ];
  // adjust href based on whether we are on root index
  const onIndex = window.location.pathname.endsWith('index.html') || window.location.pathname.endsWith('/project/') || window.location.pathname.endsWith('/');
  const adjustedLinks = links.map(l => {
    if (onIndex) {
      if (l.id === 'home') return { ...l, href: 'index.html' };
      return { ...l, href: l.href.replace('../', '') };
    }
    return l;
  });

  return (
    <header className={`nav ${dark ? 'dark' : ''} ${scrolled ? 'scrolled' : ''}`}>
      <ul className="nav-links">
        {adjustedLinks.slice(0, 4).map(l => (
          <li key={l.id}>
            <a className={`nav-link ${active === l.id ? 'active' : ''}`} href={l.href}>{l.label}</a>
          </li>
        ))}
      </ul>
      <a href={onIndex ? 'index.html' : '../index.html'} className="nav-logo">
        AURELIA
        <small>Residences · Sofia</small>
      </a>
      <div className="nav-right">
        <ul className="nav-links" style={{ gap: 28 }}>
          {adjustedLinks.slice(4).map(l => (
            <li key={l.id}>
              <a className={`nav-link ${active === l.id ? 'active' : ''}`} href={l.href}>{l.label}</a>
            </li>
          ))}
        </ul>
        <div className="lang-switch">
          <button className="active">BG</button><span>·</span>
          <button>EN</button><span>·</span>
          <button>DE</button>
        </div>
        <a href={onIndex ? 'booking/booking.html' : '../booking/booking.html'} className="nav-cta">Резервирайте оглед</a>
        <AureliaMobileMenu active={active} links={adjustedLinks} onIndex={onIndex} />
      </div>
    </header>
  );
}

/* ---------- FOOTER ---------- */
function Footer() {
  return (
    <footer className="footer grain">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-statement">
              "Една сграда живее <em>повече</em> от поколение. Ние строим за следващото."
            </div>
            <form className="footer-newsletter" onSubmit={(e) => { e.preventDefault(); alert('Записан сте за нашия newsletter.'); }}>
              <input type="email" placeholder="Електронна поща за нови проекти" required />
              <button type="submit">→ Запиши</button>
            </form>
          </div>
          <div>
            <h4>Навигация</h4>
            <ul>
              <li><a href="../index.html">Начало</a></li>
              <li><a href="../projects/projects.html">Проекти</a></li>
              <li><a href="../locations/locations.html">Локации</a></li>
              <li><a href="../investment/investment.html">Инвестиции</a></li>
              <li><a href="../about/about.html">За нас</a></li>
            </ul>
          </div>
          <div>
            <h4>Услуги</h4>
            <ul>
              <li><a href="../booking/booking.html">Резервиране</a></li>
              <li><a href="../process/process.html">Процес на покупка</a></li>
              <li><a href="../investment/investment.html">Инвестиционна програма</a></li>
              <li><a href="#">Концирж услуги</a></li>
              <li><a href="#">Виртуални обиколки</a></li>
            </ul>
          </div>
          <div>
            <h4>Офиси</h4>
            <ul>
              <li>София · бул. Витоша 89Б</li>
              <li>Пловдив · ул. Иван Вазов 23</li>
              <li>Бургас · бул. Демокрация 12</li>
              <li style={{marginTop: 16, color: 'var(--bronze-soft)'}}>+359 2 850 10 10</li>
              <li>concierge@aurelia.bg</li>
            </ul>
          </div>
          <div>
            <h4>Социални</h4>
            <ul>
              <li><a href="#">Instagram</a></li>
              <li><a href="#">LinkedIn</a></li>
              <li><a href="#">YouTube</a></li>
              <li><a href="#">Facebook</a></li>
              <li><a href="#">Houzz</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 AURELIA RESIDENCES OOD · ЕИК 207384921 · ДДС BG207384921</span>
          <div style={{ display: 'flex', gap: 32 }}>
            <a href="#">Политика за поверителност</a>
            <a href="#">Бисквитки</a>
            <a href="#">Общи условия</a>
          </div>
        </div>
      </div>
      <div className="footer-signature">AURELIA</div>
    </footer>
  );
}

/* ---------- STICKY CONCIERGE ---------- */
function StickyConcierge() {
  return (
    <a href="../booking/booking.html" className="sticky-concierge">
      <span className="sticky-concierge-dot"></span>
      <span>Концирж · Свободни сме</span>
    </a>
  );
}

/* ---------- SPLIT TEXT COMPONENT ---------- */
function SplitText({ children, className = '', tag = 'span', delay = 0 }) {
  const Tag = tag;
  const text = typeof children === 'string' ? children : '';
  return (
    <Tag className={`split-text ${className}`} data-reveal>
      {text.split('').map((c, i) => (
        <span key={i} className="char" style={{ transitionDelay: `${delay + i * 0.018}s` }}>
          {c === ' ' ? ' ' : c}
        </span>
      ))}
    </Tag>
  );
}

/* ---------- COUNTER COMPONENT ---------- */
function Counter({ to, suffix = '', prefix = '', format }) {
  const [ref, val] = useCounter(to);
  const v = format ? format(val) : Math.round(val);
  return <span ref={ref} className="counter">{prefix}{v}{suffix}</span>;
}

/* ---------- ARROW SVG ---------- */
function ArrowRight({ size = 16 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10m0 0L9 4m4 4L9 12" stroke="currentColor" strokeWidth="1.4"/>
    </svg>
  );
}
