/* Site chrome + layout helpers for the 6ft website kit. */
const { useState, useEffect, useRef } = React;
const NS = window.__FT_NS;
const { Logo, Button, Icon, Badge } = NS;
const D = window.FT_DATA;

/* --- scroll reveal: fade-in-up, played once ------------------------------- */
function Reveal({ children, delay = 0, as = 'div', style }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  const [instant, setInstant] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const vp = document.querySelector('#viewport');
    // Already on screen at mount (above the fold of a freshly opened page): let the route fade carry it, no slide.
    const r = el.getBoundingClientRect();
    if (r.top < (vp ? vp.clientHeight : innerHeight) * 0.9) { setInstant(true); setSeen(true); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
    }, { root: vp, threshold: 0.15, rootMargin: '0px 0px -8% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return <Tag ref={ref} style={{
    opacity: seen ? 1 : 0,
    transform: seen ? 'none' : 'translateY(24px)',
    transition: instant ? 'none' : 'opacity 600ms cubic-bezier(.2,0,0,1) ' + delay + 'ms, transform 600ms cubic-bezier(.2,0,0,1) ' + delay + 'ms',
    willChange: seen ? 'auto' : 'opacity, transform',
    ...style
  }}>{children}</Tag>;
}

const container = { width: '100%', maxWidth: 1280, margin: '0 auto', padding: '0 24px', boxSizing: 'border-box' };

function Section({ children, tone = 'page', pad = 128, id, style }) {
  const bg = { page: 'var(--surface-page)', card: 'var(--surface-card)', ink: 'var(--surface-ink)', brand: 'var(--gradient-yellow)' }[tone];
  return (
    <section id={id} style={{ background: bg, padding: pad + 'px 0', ...style }}>
      <div style={container}>{children}</div>
    </section>
  );
}

function Eyebrow({ children, onBrand = false }) {
  return <div style={{
    fontFamily: 'var(--font-label)', fontWeight: 700, fontSize: 12,
    letterSpacing: 'var(--tracking-widest)', textTransform: 'uppercase',
    color: onBrand ? 'rgb(0 0 0 / .6)' : 'var(--brand-yellow)', marginBottom: 16
  }}>{children}</div>;
}

function SectionHead({ eyebrow, title, lede, align = 'left', onBrand = false, max = 720 }) {
  return (
    <div style={{ maxWidth: align === 'center' ? 820 : max, margin: align === 'center' ? '0 auto' : 0, textAlign: align, marginBottom: 56 }}>
      {eyebrow ? <Eyebrow onBrand={onBrand}>{eyebrow}</Eyebrow> : null}
      <h2 style={{
        fontSize: 'clamp(30px, 3.4vw, 48px)', fontWeight: 700, letterSpacing: 'var(--tracking-tight)',
        lineHeight: 1.12, margin: 0, color: onBrand ? 'var(--text-on-brand)' : 'var(--text-primary)'
      }}>{title}</h2>
      {lede ? <p style={{
        marginTop: 20, fontSize: 20, lineHeight: 1.625, maxWidth: 720,
        marginLeft: align === 'center' ? 'auto' : 0, marginRight: align === 'center' ? 'auto' : 0,
        color: onBrand ? 'rgb(0 0 0 / .78)' : 'var(--text-secondary)'
      }}>{lede}</p> : null}
    </div>
  );
}

/* --- header --------------------------------------------------------------- */
function Header({ page, go, scrolled }) {
  const [open, setOpen] = useState(false);
  useEffect(() => { setOpen(false); }, [page]);
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 1030,
      background: scrolled ? 'rgb(38 38 38 / .88)' : 'rgb(38 38 38 / .55)',
      backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
      borderBottom: '1px solid ' + (scrolled ? 'var(--border-subtle)' : 'transparent'),
      transition: 'background var(--dur-slow) var(--ease), border-color var(--dur-slow) var(--ease)'
    }}>
      <div style={{ ...container, height: scrolled ? 64 : 76, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24, transition: 'height var(--dur-slow) var(--ease)' }}>
        <a href="#" onClick={(e) => { e.preventDefault(); go('home'); }}
          style={{ display: 'inline-flex', alignItems: 'center', gap: 12, textDecoration: 'none', color: 'var(--text-primary)' }}>
          <Logo variant="master" size={scrolled ? 34 : 40} />
          <span style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 19, letterSpacing: 'var(--tracking-tight)' }}>6ft Projects</span>
        </a>

        <nav style={{ display: 'flex', alignItems: 'center', gap: 2 }} className="ft-desktop-nav">
          {D.nav.map((n) => {
            const active = page === n.id;
            return (
              <a key={n.id} href="#" onClick={(e) => { e.preventDefault(); go(n.id); }} style={{
                position: 'relative', padding: '8px 14px', borderRadius: 'var(--radius-md)',
                fontSize: 15, fontWeight: 500, textDecoration: 'none',
                color: active ? 'var(--text-primary)' : 'var(--text-secondary)',
                transition: 'color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease)'
              }}
                onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text-primary)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.color = active ? 'var(--text-primary)' : 'var(--text-secondary)'; }}>
                {n.label}
                <span style={{
                  position: 'absolute', bottom: 1, left: '50%', transform: 'translateX(-50%)',
                  width: 4, height: 4, borderRadius: '50%', background: 'var(--brand-yellow)',
                  opacity: active ? 1 : 0, transition: 'opacity var(--dur-base) var(--ease)'
                }} />
              </a>
            );
          })}
          <span style={{ width: 1, height: 22, background: 'var(--border-default)', margin: '0 12px' }} />
          <Button variant="primary" size="sm" iconAfter="arrow-right" onClick={() => go('contact')}>Get In Touch</Button>
        </nav>

        <button aria-label="Menu" onClick={() => setOpen(!open)} className="ft-mobile-toggle" style={{
          display: 'none', width: 40, height: 40, alignItems: 'center', justifyContent: 'center',
          background: 'transparent', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)',
          color: 'var(--text-primary)', cursor: 'pointer'
        }}><Icon name={open ? 'x' : 'menu'} size={20} /></button>
      </div>

      <div className="ft-mobile-menu" style={{
        display: 'none', overflow: 'hidden', borderTop: '1px solid var(--border-subtle)',
        maxHeight: open ? 380 : 0, transition: 'max-height var(--dur-slow) var(--ease)'
      }}>
        <div style={{ ...container, padding: '12px 24px 20px', display: 'flex', flexDirection: 'column', gap: 4 }}>
          {[{ id: 'home', label: 'Home' }].concat(D.nav).map((n) => (
            <a key={n.id} href="#" onClick={(e) => { e.preventDefault(); go(n.id); }} style={{
              padding: '12px 14px', borderRadius: 'var(--radius-md)', textDecoration: 'none', fontSize: 16, fontWeight: 500,
              color: page === n.id ? 'var(--brand-yellow)' : 'var(--text-secondary)',
              background: page === n.id ? 'var(--accent-soft)' : 'transparent'
            }}>{n.label}</a>
          ))}
          <div style={{ marginTop: 8 }}><Button variant="primary" fullWidth onClick={() => go('contact')}>Get In Touch</Button></div>
        </div>
      </div>
    </header>
  );
}

/* --- footer --------------------------------------------------------------- */
function Footer({ go }) {
  const col = { display: 'flex', flexDirection: 'column', gap: 12 };
  const title = { fontFamily: 'var(--font-heading)', fontSize: 17, fontWeight: 700, marginBottom: 4 };
  const link = { fontSize: 14, color: 'var(--text-secondary)', textDecoration: 'none' };
  return (
    <footer style={{ background: 'var(--surface-card)', borderTop: '1px solid var(--border-default)' }}>
      <div style={{ ...container, padding: '64px 24px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 40 }}>
          <div style={col}>
            <div style={{ fontFamily: 'var(--font-heading)', fontSize: 21, fontWeight: 700, color: 'var(--brand-yellow)' }}>6ft Projects</div>
            <p style={{ fontSize: 14, lineHeight: 1.625, color: 'var(--text-secondary)' }}>{D.company.legal}</p>
            <p style={{ fontSize: 14, lineHeight: 1.625, color: 'var(--text-secondary)' }}>Expert project management consultancy delivering results across construction, IT, and business operations.</p>
            <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
              {D.certifications.filter((c) => c.held).map((c) => <Badge key={c.code} tone="brandOutline" size="sm" icon="badge-check">{c.code}</Badge>)}
            </div>
          </div>
          <div style={col}>
            <div style={title}>Company</div>
            {[{ id: 'about', label: 'About Us' }, { id: 'services', label: 'Services' }, { id: 'industries', label: 'Industries' }, { id: 'projects', label: 'Projects' }, { id: 'certifications', label: 'Certifications' }].map((l) => (
              <a key={l.id} href="#" style={link} onClick={(e) => { e.preventDefault(); go(l.id); }}>{l.label}</a>
            ))}
          </div>
          <div style={col}>
            <div style={title}>Legal</div>
            <a href="#privacy" style={link} onClick={(e) => { e.preventDefault(); go('privacy'); }}>Privacy Policy</a>
            <a href="#terms" style={link} onClick={(e) => { e.preventDefault(); go('terms'); }}>Terms of Service</a>
          </div>
          <div style={col}>
            <div style={title}>Contact</div>
            {[['map-pin', D.company.address], ['mail', D.company.email], ['globe', D.company.site], ['linkedin', D.company.linkedin]].map(([ic, tx]) => (
              <div key={tx} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <span style={{ color: 'var(--brand-yellow)', flexShrink: 0, marginTop: 2 }}><Icon name={ic} size={18} /></span>
                <span style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.5 }}>{tx}</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{ borderTop: '1px solid var(--border-default)', marginTop: 40, paddingTop: 24, textAlign: 'center', fontSize: 13, color: 'var(--text-muted)' }}>
          © {new Date().getFullYear()} {D.company.legal}. All rights reserved.
        </div>
      </div>
    </footer>
  );
}

/* --- reusable page hero --------------------------------------------------- */
function PageHero({ eyebrow, title, lede, tone = 'card', photo, children }) {
  const isBrand = tone === 'brand';
  return (
    <section style={{
      position: 'relative', overflow: 'hidden',
      background: isBrand ? 'var(--gradient-yellow)' : 'var(--surface-card)',
      padding: '128px 0 80px'
    }}>
      {photo ? (
        <div style={{ position: 'absolute', inset: 0 }}>
          <img src={'./assets/photography/' + photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', filter: 'grayscale(1)' }} />
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(90deg, rgb(0 0 0 / .88) 0%, rgb(0 0 0 / .72) 55%, rgb(0 0 0 / .45) 100%)' }} />
        </div>
      ) : null}
      <div style={{ ...container, position: 'relative' }}>
        {eyebrow ? <Eyebrow onBrand={isBrand}>{eyebrow}</Eyebrow> : null}
        <h1 style={{
          fontSize: 'clamp(36px, 5vw, 60px)', fontWeight: 700, letterSpacing: 'var(--tracking-tight)',
          lineHeight: 1.08, margin: 0, maxWidth: 900, color: isBrand ? 'var(--text-on-brand)' : 'var(--text-primary)'
        }}>{title}</h1>
        {lede ? <p style={{
          marginTop: 22, fontSize: 20, lineHeight: 1.625, maxWidth: 768,
          color: isBrand ? 'rgb(0 0 0 / .78)' : 'var(--text-secondary)'
        }}>{lede}</p> : null}
        {children}
      </div>
    </section>
  );
}

Object.assign(window, { Reveal, Section, SectionHead, Eyebrow, Header, Footer, PageHero, ftContainer: container });
