// Responsive primitives for RangehandIQ.
//
// Strategy: viewport hook + breakpoint helpers so every section can pick
// padding/grid templates per viewport, plus clamp() for fluid type. No more
// `@media (max-width:768px)` override block — components carry their own
// responsive logic.
//
// Breakpoints:
//   < 640   mobile   (single column, stacked, hamburger nav, paddings 24px)
//   640-1024 tablet  (compressed desktop, hamburger nav still on, paddings 40px)
//   ≥ 1024  desktop  (full editorial grid, paddings 64-80px, link bar nav)

const RANCH_BP = { mobile: 640, tablet: 1024 };

// Read the viewport once on first render, subscribe to resize.
function useViewport() {
  const get = () => {
    if (typeof window === 'undefined') {
      return { w: 1440, h: 900, isMobile: false, isTablet: false, isDesktop: true };
    }
    const w = window.innerWidth;
    const h = window.innerHeight;
    return {
      w, h,
      isMobile: w < RANCH_BP.mobile,
      isTablet: w >= RANCH_BP.mobile && w < RANCH_BP.tablet,
      isDesktop: w >= RANCH_BP.tablet,
    };
  };
  const [vp, setVp] = React.useState(get);
  React.useEffect(() => {
    let raf = 0;
    const onResize = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setVp(get()));
    };
    window.addEventListener('resize', onResize);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', onResize);
    };
  }, []);
  return vp;
}

// r(mobile, tablet, desktop) — pick a value per viewport.
// Tablet falls through to desktop if undefined; mobile must be supplied.
function rv(vp, m, t, d) {
  if (vp.isMobile) return m;
  if (vp.isTablet) return t === undefined ? d : t;
  return d;
}

// Section outer padding: vertical x horizontal.
// Mobile 64/24, tablet 88/40, desktop 120/64.
function sectionPad(vp, { topD = 120, botD = 110, hD = 64 } = {}) {
  if (vp.isMobile) return `${Math.round(topD * 0.55)}px 24px ${Math.round(botD * 0.55)}px`;
  if (vp.isTablet) return `${Math.round(topD * 0.78)}px 40px ${Math.round(botD * 0.78)}px`;
  return `${topD}px ${hD}px ${botD}px`;
}

// Eyebrow + content split. On mobile: stack, eyebrow becomes a thin label
// row above the heading. On tablet/desktop: 160px / 1fr grid as today.
function splitGrid(vp, leftCol = '160px', gap = 48) {
  if (vp.isMobile) return { display: 'flex', flexDirection: 'column', gap: 20 };
  if (vp.isTablet) return { display: 'grid', gridTemplateColumns: '120px 1fr', gap: 32 };
  return { display: 'grid', gridTemplateColumns: `${leftCol} 1fr`, gap };
}

// Empty gutter cell (used to align inner grids under a content column).
// Returns null on mobile so the cell collapses out of the flex stack.
function GutterCell({ vp }) {
  if (vp.isMobile) return null;
  return <div />;
}

// Clamp helper for fluid type. Pass desktop size; min is computed.
// fluid(64) → "clamp(36px, 6.5vw, 64px)"
function fluid(desktopPx, { minRatio = 0.56, vw } = {}) {
  const min = Math.round(desktopPx * minRatio);
  const v = vw != null ? vw : Math.max(4.5, Math.round(desktopPx / 11 * 10) / 10);
  return `clamp(${min}px, ${v}vw, ${desktopPx}px)`;
}

// ─────────────────────────────────────────────────────────────────────────
// Hamburger nav. Used on mobile + tablet. Desktop keeps the link bar.
// Tokens come from heroes.jsx (RANCH_TOKENS, sansStack, LogoLockup) — those
// are global by the time this file's components render.

const DEFAULT_NAV_ITEMS_RV = [
  { label: 'The problem',       href: '#problem'  },
  { label: 'The ask',           href: '#ask'      },
  { label: 'How it works',      href: '#how-it-works' },
  { label: 'What else it does', href: '#features' },
  { label: 'The report',        href: '#report'   },
  { label: 'Who it\u2019s for',      href: '#personas' },
  { label: 'Our story',         href: '#lineage'  },
  { label: 'Request access',    href: '#early-access' },
];

function ResponsiveNav({ inverted = false, items = DEFAULT_NAV_ITEMS_RV, lockupHeight = 140 }) {
  const vp = useViewport();
  const [open, setOpen] = React.useState(false);

  // Lock body scroll while menu is open.
  React.useEffect(() => {
    if (!open) return;
    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]);

  const ink = inverted ? RANCH_TOKENS.paper : RANCH_TOKENS.ink;
  const hair = inverted ? 'rgba(241,233,212,.5)' : RANCH_TOKENS.hairStrong;
  const links = items.slice(0, -1);
  const cta = items[items.length - 1];

  // Desktop link bar — unchanged from original Nav, just cleaner.
  if (vp.isDesktop) {
    return (
      <nav style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '20px 56px', position: 'relative', zIndex: 2,
      }}>
        <LogoLockup inverted={inverted} height={lockupHeight} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 36 }}>
          {links.map((it) => (
            <a key={it.label} href={it.href} style={{
              fontFamily: sansStack, fontSize: 13, fontWeight: 500,
              color: ink, textDecoration: 'none', letterSpacing: '0.002em',
            }}>{it.label}</a>
          ))}
          <a href={cta.href} style={{
            fontFamily: sansStack, fontSize: 13, fontWeight: 500,
            color: ink, textDecoration: 'none',
            padding: '8px 16px',
            border: `1px solid ${hair}`,
            borderRadius: 999,
          }}>{cta.label}</a>
        </div>
      </nav>
    );
  }

  // Mobile + tablet — logo + hamburger button. Open → fullscreen panel.
  const padX = vp.isTablet ? 32 : 20;
  const padY = vp.isTablet ? 18 : 14;
  const lockupH = vp.isTablet ? 110 : 88;

  return (
    <nav style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: `${padY}px ${padX}px`, position: 'relative', zIndex: 50,
    }}>
      <LogoLockup inverted={inverted} height={lockupH} />
      <button
        aria-label={open ? 'Close menu' : 'Open menu'}
        aria-expanded={open}
        onClick={() => setOpen(!open)}
        style={{
          background: 'transparent', border: `1px solid ${hair}`,
          borderRadius: 2, width: 44, height: 44, padding: 0,
          cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          color: ink,
        }}
      >
        <span style={{ position: 'relative', display: 'inline-block', width: 18, height: 12 }}>
          <span style={{
            position: 'absolute', left: 0, right: 0, height: 1.5, background: ink,
            top: open ? 5 : 0,
            transform: open ? 'rotate(45deg)' : 'none',
            transition: 'top .2s ease, transform .2s ease',
          }} />
          <span style={{
            position: 'absolute', left: 0, right: 0, height: 1.5, background: ink,
            top: 5,
            opacity: open ? 0 : 1,
            transition: 'opacity .15s ease',
          }} />
          <span style={{
            position: 'absolute', left: 0, right: 0, height: 1.5, background: ink,
            top: open ? 5 : 11,
            transform: open ? 'rotate(-45deg)' : 'none',
            transition: 'top .2s ease, transform .2s ease',
          }} />
        </span>
      </button>

      {open && (
        <div role="dialog" aria-modal="true" style={{
          position: 'fixed', inset: 0, zIndex: 100,
          background: inverted ? RANCH_TOKENS.ink : RANCH_TOKENS.paper,
          display: 'flex', flexDirection: 'column',
          animation: 'rhq-fade .18s ease',
        }}>
          {/* Top row inside the menu — mirror the closed state */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: `${padY}px ${padX}px`,
            borderBottom: `1px solid ${inverted ? 'rgba(241,233,212,.12)' : RANCH_TOKENS.hair}`,
          }}>
            <LogoLockup inverted={inverted} height={lockupH} onClick={() => setOpen(false)} />
            <button
              aria-label="Close menu"
              onClick={() => setOpen(false)}
              style={{
                background: 'transparent', border: `1px solid ${hair}`,
                borderRadius: 2, width: 44, height: 44, padding: 0,
                cursor: 'pointer', color: ink,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}
            >
              <span style={{ position: 'relative', display: 'inline-block', width: 18, height: 12 }}>
                <span style={{ position: 'absolute', left: 0, right: 0, height: 1.5, background: ink, top: 5, transform: 'rotate(45deg)' }} />
                <span style={{ position: 'absolute', left: 0, right: 0, height: 1.5, background: ink, top: 5, transform: 'rotate(-45deg)' }} />
              </span>
            </button>
          </div>

          {/* Links */}
          <div style={{
            flex: 1, overflowY: 'auto',
            padding: '24px 24px 32px',
            display: 'flex', flexDirection: 'column',
          }}>
            {links.map((it) => (
              <a key={it.label} href={it.href} onClick={() => setOpen(false)} style={{
                fontFamily: sansStack, fontWeight: 400,
                fontSize: vp.isTablet ? 32 : 28, lineHeight: 1.1, letterSpacing: '-0.014em',
                color: ink, textDecoration: 'none',
                padding: '18px 0',
                borderBottom: `1px solid ${inverted ? 'rgba(241,233,212,.12)' : RANCH_TOKENS.hair}`,
              }}>{it.label}</a>
            ))}

            <a href={cta.href} onClick={() => setOpen(false)} style={{
              marginTop: 32,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              fontFamily: sansStack, fontSize: 15, fontWeight: 500,
              color: RANCH_TOKENS.paper, background: RANCH_TOKENS.brandRed,
              textDecoration: 'none', letterSpacing: '0.005em',
              padding: '18px 24px', borderRadius: 2,
              minHeight: 52,
            }}>
              {cta.label}
              <span style={{ fontSize: 16, lineHeight: 1, marginTop: -1 }}>&rarr;</span>
            </a>

            <div style={{
              marginTop: 'auto', paddingTop: 32,
              fontFamily: monoStack, fontSize: 10,
              color: inverted ? 'oklch(0.70 0.020 70)' : RANCH_TOKENS.inkMute,
              letterSpacing: '0.16em', textTransform: 'uppercase',
            }}>
              Now in private beta &middot; Park Valley, UT
            </div>
          </div>
        </div>
      )}
    </nav>
  );
}

Object.assign(window, {
  RANCH_BP, useViewport, rv, sectionPad, splitGrid, GutterCell, fluid,
  ResponsiveNav, DEFAULT_NAV_ITEMS_RV,
});
