/* global React */
// Cowles Strategic Advisory — single-page site components.

const { useState, useEffect, useRef } = React;

// Sections used by the in-page nav.
const SECTIONS = [
  { id: 'practice',    label: 'Practice' },
  { id: 'approach',    label: 'Approach' },
  { id: 'engagements', label: 'Engagements' },
  { id: 'contact',     label: 'Contact' },
];

/* ---------------------------------------------------------------- */
/* Phase 11: Scroll-triggered fade-up reveal hook                   */
/* ---------------------------------------------------------------- */
function useReveal(threshold = 0.1) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (prefersReduced) { setVisible(true); return; }
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); obs.disconnect(); } },
      { threshold }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, visible];
}

/* ---------------------------------------------------------------- */
/* Decorative bar-chart motif used on Navy panels                    */
/* ---------------------------------------------------------------- */
function BarsMotif({ className = '', style = {}, opacity = 0.18 }) {
  return (
    <svg className={className} style={{ opacity, ...style }} viewBox="0 0 640 540" aria-hidden="true" preserveAspectRatio="xMidYMid slice">
      <rect x="40"  y="320" width="80" height="180" fill="#185FA5"></rect>
      <rect x="160" y="240" width="80" height="260" fill="#378ADD"></rect>
      <rect x="280" y="160" width="80" height="340" fill="#5DCAA5"></rect>
      <rect x="400" y="60"  width="80" height="440" fill="#5DCAA5"></rect>
      <path d="M40 460 Q260 200 480 100" stroke="#fff" strokeWidth="6" fill="none" opacity="0.7"></path>
    </svg>
  );
}

/* ---------------------------------------------------------------- */
/* Lucide icon wrapper — relies on global `lucide` UMD              */
/* ---------------------------------------------------------------- */
function Icon({ name, className = '', style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && typeof window.lucide.createIcons === 'function') {
      window.lucide.createIcons({ icons: window.lucide.icons, nameAttr: 'data-lucide' });
    }
  }, [name]);
  return <i ref={ref} data-lucide={name} className={className} style={style}></i>;
}

/* ---------------------------------------------------------------- */
/* Smooth-scroll to an in-page section                               */
/* ---------------------------------------------------------------- */
function scrollToSection(id) {
  if (id === 'top') {
    window.scrollTo({ top: 0, behavior: 'smooth' });
    return;
  }
  const el = document.getElementById(id);
  if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

/* ---------------------------------------------------------------- */
/* Header — sticky, anchor-link nav, active section highlight       */
/* Phase 11.3: Compact on scroll; Phase 12.4: aria-current          */
/* ---------------------------------------------------------------- */
function Header() {
  const [active, setActive] = useState('top');
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const ids = SECTIONS.map(s => s.id);

    const onScroll = () => {
      const offset = 120;
      let current = 'top';
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        if (el.getBoundingClientRect().top - offset <= 0) current = id;
      }
      setActive(current);
      setScrolled(window.scrollY > 80);
    };

    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header className={`site-header${scrolled ? ' scrolled' : ''}`}>
      <div className="container row">
        <a
          className="logo"
          href="#top"
          onClick={(e) => { e.preventDefault(); scrollToSection('top'); }}
          aria-label="Cowles Strategic Advisory home"
        >
          <img src="assets/logo-horizontal.png" alt="Cowles Strategic Advisory" />
        </a>
        <nav aria-label="Site navigation">
          {SECTIONS.map(s => (
            <a
              key={s.id}
              href={`#${s.id}`}
              className={active === s.id ? 'active' : ''}
              aria-current={active === s.id ? 'page' : undefined}
              onClick={(e) => { e.preventDefault(); scrollToSection(s.id); }}
            >{s.label}</a>
          ))}
        </nav>
      </div>
    </header>
  );
}

/* ---------------------------------------------------------------- */
/* Footer — Phase 10: 3-column, dynamic year, Privacy link          */
/* ---------------------------------------------------------------- */
function Footer() {
  const year = new Date().getFullYear();
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="grid">
          <div>
            <img src="assets/logo-horizontal.png" alt="Cowles Strategic Advisory" style={{ height: 32, display: 'block' }} />
            <div className="tagline">"Clarity of Purpose. Confidence in Direction."</div>
            <div className="contact-info" style={{ marginTop: 24 }}>
              <a href="mailto:chris@cowlesadvisory.com">chris@cowlesadvisory.com</a><br />
              By appointment · Cheshire, CT
            </div>
          </div>
          <div>
            <h5>Navigate</h5>
            <ul>
              <li><a href="#practice"    onClick={(e) => { e.preventDefault(); scrollToSection('practice'); }}>Practice</a></li>
              <li><a href="#approach"    onClick={(e) => { e.preventDefault(); scrollToSection('approach'); }}>Approach</a></li>
              <li><a href="#engagements" onClick={(e) => { e.preventDefault(); scrollToSection('engagements'); }}>Engagements</a></li>
              <li><a href="#contact"     onClick={(e) => { e.preventDefault(); scrollToSection('contact'); }}>Contact</a></li>
            </ul>
          </div>
          <div>
            <h5>Practice</h5>
            <ul>
              <li><a href="#practice" onClick={(e) => { e.preventDefault(); scrollToSection('practice'); }}>Corporate strategy</a></li>
              <li><a href="#practice" onClick={(e) => { e.preventDefault(); scrollToSection('practice'); }}>Acquisitions &amp; divestitures</a></li>
              <li><a href="#practice" onClick={(e) => { e.preventDefault(); scrollToSection('practice'); }}>Strategic due diligence</a></li>
              <li><a href="#practice" onClick={(e) => { e.preventDefault(); scrollToSection('practice'); }}>Board advisory</a></li>
            </ul>
          </div>
        </div>
        <div className="legal">
          <div>© {year} Cowles Strategic Advisory, LLC. All rights reserved.</div>
          <a href="#" onClick={(e) => e.preventDefault()}>Privacy</a>
        </div>
      </div>
    </footer>
  );
}

/* ---------------------------------------------------------------- */
/* Form primitives                                                   */
/* ---------------------------------------------------------------- */
function Button({ children, variant = 'primary', onClick, type = 'button', href }) {
  if (href) {
    return (
      <a href={href} className={`btn btn--${variant}`} onClick={onClick}>{children}</a>
    );
  }
  return (
    <button type={type} className={`btn btn--${variant}`} onClick={onClick}>{children}</button>
  );
}

function Field({ label, type = 'text', value, onChange, placeholder, help, required, as = 'input', children }) {
  return (
    <div className="field">
      <label>{label}{required ? ' *' : ''}</label>
      {as === 'select' ? (
        <select value={value} onChange={onChange}>{children}</select>
      ) : as === 'textarea' ? (
        <textarea value={value} onChange={onChange} placeholder={placeholder} />
      ) : (
        <input type={type} value={value} onChange={onChange} placeholder={placeholder} />
      )}
      {help && <div className="help">{help}</div>}
    </div>
  );
}

Object.assign(window, { Header, Footer, Button, Field, Icon, BarsMotif, scrollToSection, useReveal });
