/* Shared UI: Nav, Footer, Placeholder, reveal hooks */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// --- Intersection reveal hook ---
function useReveal(once = true) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    // Fallback: if IO doesn't fire within 1.2s, force reveal so content is never hidden.
    const fallback = setTimeout(() => {
      if (!el.classList.contains('in')) el.classList.add('in');
    }, 1200);

    // If the element is already (partially) on screen at mount, reveal immediately.
    const r = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (r.top < vh && r.bottom > 0) {
      // next frame so the initial styles paint first, then transition runs
      requestAnimationFrame(() => el.classList.add('in'));
    }

    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          el.classList.add('in');
          if (once) io.unobserve(el);
        } else if (!once) {
          el.classList.remove('in');
        }
      });
    }, { threshold: 0, rootMargin: '0px 0px -10% 0px' });
    io.observe(el);

    return () => { io.disconnect(); clearTimeout(fallback); };
  }, [once]);
  return ref;
}

function Reveal({ children, className = '', as: Tag = 'div', stagger = false, style }) {
  const ref = useReveal();
  return (
    <Tag ref={ref} className={`${stagger ? 'reveal-stagger' : 'reveal'} ${className}`} style={style}>
      {children}
    </Tag>
  );
}

function MaskLine({ children, delay = 0, className = '' }) {
  const ref = useReveal();
  return (
    <span ref={ref} className={`mask-line d${delay} ${className}`}>
      <span>{children}</span>
    </span>
  );
}

// --- Placeholder imagery ---
function Photo({ variant = 'stripes', tag, caption, ratio = '3/4', style = {}, className = '' }) {
  return (
    <div
      className={`photo ${variant} ${className}`}
      style={{ aspectRatio: ratio, ...style }}
    >
      {tag && <div className="photo-tag">{tag}</div>}
      {caption && <div className="photo-caption">{caption}</div>}
    </div>
  );
}

// --- Navigation ---
function Nav({ current }) {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-left">
          <a href="index.html" className={`nav-link ${current === 'home' ? 'active' : ''}`}>Home</a>
          <a href="the-face-edit.html" className={`nav-link ${current === 'workshops' ? 'active' : ''}`}>The Face Edit</a>
          <a href="about.html" className={`nav-link ${current === 'about' ? 'active' : ''}`}>About</a>
        </div>
        <a href="index.html" className="wordmark">
          KYLIE NOLAN
          <span className="mark-line">Makeup Artist · The Face Edit</span>
        </a>
        <div className="nav-right">
          <span className="mono">Waitlist open</span>
          <a href="#waitlist" className="btn" style={{ padding: '10px 16px', fontSize: '10.5px' }}>
            Join Waitlist
          </a>
        </div>
      </div>
    </nav>
  );
}

// --- Footer ---
function Footer() {
  return (
    <footer style={{ background: 'var(--ink)', color: 'rgba(255,255,255,0.86)', marginTop: '8rem' }}>
      <div className="container" style={{ padding: '6rem var(--gutter) 2.5rem' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: '3rem', alignItems: 'start' }}>
          <div>
            <div className="display" style={{ fontSize: 'clamp(40px, 6vw, 88px)', lineHeight: 0.9, color: 'white' }}>
              Makeup,<br /><em>edited</em> for you.
            </div>
            <div className="mono" style={{ color: 'rgba(255,255,255,0.5)', marginTop: '2rem' }}>
              The Face Edit · By Kylie Nolan
            </div>
          </div>
          <FooterCol title="Explore" items={[
            ['Home','index.html'],['The Face Edit','the-face-edit.html'],['About Kylie','about.html']
          ]} />
          <FooterCol title="Method" items={[
            ['Contrast','the-face-edit.html#method'],['Colour','the-face-edit.html#method'],['Balance','the-face-edit.html#method']
          ]} />
          <ContactCol />
        </div>

        <div style={{
          marginTop: '5rem', paddingTop: '2rem',
          borderTop: '1px solid rgba(255,255,255,0.12)',
          fontFamily: 'var(--f-mono)', fontSize: '10.5px', letterSpacing: '0.18em',
          textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)'
        }}>
          <span>© 2026 TK Publications. All rights reserved.</span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items }) {
  return (
    <div>
      <div className="mono" style={{ color: 'rgba(255,255,255,0.4)', marginBottom: '1.25rem' }}>{title}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.7rem' }}>
        {items.map(([label, href]) => (
          <li key={label}>
            <a href={href} style={{ color: 'rgba(255,255,255,0.86)', fontSize: '14px', letterSpacing: '0.01em' }}>
              {label}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ContactCol() {
  const linkStyle = {
    width: 44, height: 44,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    border: '1px solid rgba(255,255,255,0.18)',
    borderRadius: '50%',
    color: 'rgba(255,255,255,0.86)',
    transition: 'background 0.3s var(--ease-out), color 0.3s var(--ease-out), border-color 0.3s var(--ease-out)'
  };
  const onEnter = (e) => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = 'var(--ink)'; e.currentTarget.style.borderColor = 'white'; };
  const onLeave = (e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(255,255,255,0.86)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.18)'; };
  return (
    <div>
      <div className="mono" style={{ color: 'rgba(255,255,255,0.4)', marginBottom: '1.25rem' }}>Contact</div>
      <div style={{ display: 'flex', gap: '0.6rem', flexWrap: 'wrap' }}>
        <a href="mailto:hello@thefaceedit.com.au" aria-label="Email The Face Edit" title="hello@thefaceedit.com.au" style={linkStyle} onMouseEnter={onEnter} onMouseLeave={onLeave}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <rect x="3" y="5" width="18" height="14" rx="1.5"/>
            <path d="M3.5 6.5l8.5 7 8.5-7"/>
          </svg>
        </a>
        <a href="https://www.instagram.com/kylie_nolan/" target="_blank" rel="noopener" aria-label="Instagram" title="@kylie_nolan" style={linkStyle} onMouseEnter={onEnter} onMouseLeave={onLeave}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <rect x="3" y="3" width="18" height="18" rx="4.5"/>
            <circle cx="12" cy="12" r="4"/>
            <circle cx="17.5" cy="6.5" r="0.6" fill="currentColor"/>
          </svg>
        </a>
        <a href="https://www.tiktok.com/@kylienolan34" target="_blank" rel="noopener" aria-label="TikTok" title="@kylienolan34" style={linkStyle} onMouseEnter={onEnter} onMouseLeave={onLeave}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M14 4v10.2a3.3 3.3 0 1 1-3.3-3.3"/>
            <path d="M14 4c.3 2.4 2.1 4.2 4.5 4.5"/>
          </svg>
        </a>
      </div>
      <div className="mono" style={{ color: 'rgba(255,255,255,0.5)', marginTop: '1.25rem', fontSize: '10.5px' }}>
        hello@thefaceedit.com.au
      </div>
    </div>
  );
}

// --- Marquee ---
function Marquee({ items }) {
  const content = items.map((t, i) => (
    <span key={i}>{t}<span className="marquee-dot"/></span>
  ));
  return (
    <div className="marquee">
      <div className="marquee-track">
        {content}{content}{content}{content}
      </div>
    </div>
  );
}

// --- Tweaks panel ---
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "type": "editorial",
  "pink": "soft",
  "hero": "side-by-side"
}/*EDITMODE-END*/;

function useTweaks() {
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [editMode, setEditMode] = useState(false);

  // Apply to <html> dataset
  useEffect(() => {
    const root = document.documentElement;
    root.dataset.type = tweaks.type;
    root.dataset.pink = tweaks.pink;
    root.dataset.hero = tweaks.hero;
  }, [tweaks]);

  // Host protocol
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setEditMode(true);
      if (d.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const update = useCallback((key, value) => {
    setTweaks(t => {
      const next = { ...t, [key]: value };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
      return next;
    });
  }, []);

  return { tweaks, editMode, update };
}

function TweaksPanel({ tweaks, update }) {
  const opt = (label, key, val) => (
    <button
      key={val}
      className={tweaks[key] === val ? 'on' : ''}
      onClick={() => update(key, val)}
    >{label}</button>
  );
  return (
    <div className="tweaks">
      <div className="tweaks-title">
        <span>Tweaks</span>
        <span>{Object.values(tweaks).join(' · ')}</span>
      </div>
      <div className="tweak-row">
        <span className="tweak-label">Type pairing</span>
        <div className="tweak-opts">
          {opt('Editorial', 'type', 'editorial')}
          {opt('Didone', 'type', 'didone')}
          {opt('All-sans', 'type', 'all-sans')}
          {opt('Serif+Sans', 'type', 'serif-sans')}
        </div>
      </div>
      <div className="tweak-row">
        <span className="tweak-label">Pink intensity</span>
        <div className="tweak-opts">
          {opt('Off', 'pink', 'off')}
          {opt('Whisper', 'pink', 'whisper')}
          {opt('Soft', 'pink', 'soft')}
          {opt('Anchor', 'pink', 'anchor')}
        </div>
      </div>
      <div className="tweak-row">
        <span className="tweak-label">Home hero</span>
        <div className="tweak-opts">
          {opt('Side-by-side', 'hero', 'side-by-side')}
          {opt('Portrait', 'hero', 'portrait')}
          {opt('Type-led', 'hero', 'type-led')}
        </div>
      </div>
    </div>
  );
}

// Expose
Object.assign(window, {
  useReveal, Reveal, MaskLine, Photo,
  Nav, Footer, Marquee,
  useTweaks, TweaksPanel, TWEAK_DEFAULTS
});
