// grittt landing — shared UI primitives, nav + hero (Warm Coach)
// Exported to window so the sibling babel scripts can use them.

const L = {
  bg:    '#ECE8DC',
  cream: '#F5F1E8',
  card:  '#FFFFFF',
  ink:   '#14110D',
  ink2:  '#5C544A',
  ink3:  '#A39B8E',
  rule:  '#E0D8C6',
  hype:  '#B8F23A',
  good:  '#22A664',
  warn:  '#F0A12E',
  bad:   '#E84A4A',
  display: '"Bricolage Grotesque", system-ui',
  body:   '"Geist", system-ui',
  mono:   '"Geist Mono", monospace',
};

// ── Responsive helper — true once viewport width <= breakpoint ──
function useIsMobile(breakpoint = 760) {
  const [isMobile, setIsMobile] = React.useState(() =>
    typeof window !== 'undefined' && window.innerWidth <= breakpoint
  );
  React.useEffect(() => {
    const mq = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const onChange = () => setIsMobile(mq.matches);
    onChange();
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, [breakpoint]);
  return isMobile;
}

// A live app screen scaled into a fixed, non-interactive shot box.
// Pass `clip` (in unscaled px, out of H=874) to crop the phone to just its top portion.
function PhoneShot({ children, scale = 0.6, clip }) {
  const isMobile = useIsMobile(760);
  const W = 402, H = 874;
  const s = isMobile ? scale * 0.9 : scale;
  const outerH = (clip ?? H) * s;
  return (
    <div style={{
      width: W * s, height: outerH,
      position: 'relative', flex: '0 0 auto', pointerEvents: 'none',
      overflow: clip ? 'hidden' : 'visible',
      borderTopLeftRadius: clip ? 48 * s : 0,
      borderTopRightRadius: clip ? 48 * s : 0,
    }}>
      <div style={{ width: W, height: H, transform: `scale(${s})`, transformOrigin: 'top left' }}>
        <IOSDevice width={W} height={H}>{children}</IOSDevice>
      </div>
    </div>
  );
}

function Wordmark({ size = 22, color = L.ink }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline',
      fontFamily: L.display, fontWeight: 800, fontSize: size,
      letterSpacing: '-0.04em', color, lineHeight: 1, userSelect: 'none',
    }}>
      grittt
      <span style={{
        width: size * 0.16, height: size * 0.16, borderRadius: '50%',
        background: L.hype, marginLeft: 2, alignSelf: 'flex-end', marginBottom: size * 0.12,
      }} />
    </div>
  );
}

function Btn({ children, kind = 'solid', big = false, onClick }) {
  const base = {
    fontFamily: L.display, fontWeight: 700, fontSize: big ? 17 : 14,
    letterSpacing: '-0.01em', borderRadius: 999,
    padding: big ? '16px 28px' : '11px 20px',
    cursor: 'pointer', border: 'none', whiteSpace: 'nowrap',
    transition: 'transform .12s ease, background .15s ease, color .15s ease',
    display: 'inline-flex', alignItems: 'center', gap: 8,
  };
  const kinds = {
    solid: { background: L.ink, color: '#fff' },
    lime:  { background: L.hype, color: L.ink },
    ghost: { background: 'transparent', color: L.ink, border: `1.5px solid ${L.rule}` },
  };
  return (
    <button
      onClick={onClick}
      style={{ ...base, ...kinds[kind] }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-2px)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; }}
    >{children}</button>
  );
}

// eyebrow / step label
function Eyebrow({ children, color = L.ink3, style }) {
  return (
    <div style={{
      fontFamily: L.mono, fontSize: 12, fontWeight: 600, letterSpacing: '0.14em',
      textTransform: 'uppercase', color, ...style,
    }}>{children}</div>
  );
}

// round nav arrow used by carousel
function RoundArrow({ dir, onClick, disabled }) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={{
        width: 48, height: 48, borderRadius: '50%',
        cursor: disabled ? 'default' : 'pointer',
        background: disabled ? 'transparent' : L.card,
        border: `1px solid ${L.rule}`, color: L.ink,
        opacity: disabled ? 0.35 : 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background .15s ease',
      }}
      onMouseEnter={(e) => { if (!disabled) e.currentTarget.style.background = L.hype; }}
      onMouseLeave={(e) => { if (!disabled) e.currentTarget.style.background = L.card; }}
      aria-label={dir < 0 ? 'previous' : 'next'}
    >
      <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ transform: dir < 0 ? 'scaleX(-1)' : 'none' }}>
        <path d="M9 6l6 6-6 6" />
      </svg>
    </button>
  );
}

// ── Get Beta — email capture popover ─────────────────
function GetBetaForm() {
  const [open, setOpen] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!email.trim()) return;
    setSubmitted(true);
  };

  return (
    <div style={{ position: 'relative' }}>
      <Btn kind="solid" onClick={() => setOpen((o) => !o)}>Get Beta</Btn>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 10px)', right: 0, zIndex: 60,
          width: 260, maxWidth: 'calc(100vw - 40px)', background: L.card,
          border: `1px solid ${L.rule}`, borderRadius: 16, padding: 16,
          boxShadow: '0 16px 40px rgba(20,17,13,0.16)',
        }}>
          {submitted ? (
            <div style={{ fontFamily: L.body, fontSize: 14, lineHeight: 1.5, color: L.ink }}>
              Thanks for registering. Will soon share the app details.
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              <div style={{ fontFamily: L.body, fontSize: 13, color: L.ink2, marginBottom: 10, lineHeight: 1.4 }}>
                Get early access to grittt.
              </div>
              <input
                type="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@email.com"
                style={{
                  width: '100%', boxSizing: 'border-box', fontFamily: L.body, fontSize: 14,
                  color: L.ink, background: L.bg, border: `1px solid ${L.rule}`,
                  borderRadius: 10, padding: '10px 12px', outline: 'none', marginBottom: 10,
                }}
              />
              <button type="submit" style={{
                width: '100%', fontFamily: L.display, fontWeight: 700, fontSize: 14,
                letterSpacing: '-0.01em', borderRadius: 999, padding: '11px 20px',
                cursor: 'pointer', border: 'none', background: L.hype, color: L.ink,
              }}>Get Beta</button>
            </form>
          )}
        </div>
      )}
    </div>
  );
}

// ── Nav ───────────────────────────────────────────────
function Nav() {
  const link = { fontFamily: L.body, fontSize: 14, fontWeight: 500, color: L.ink2, textDecoration: 'none', whiteSpace: 'nowrap' };
  const isMobile = useIsMobile(760);
  const [open, setOpen] = React.useState(false);
  const [hidden, setHidden] = React.useState(false);

  React.useEffect(() => { if (!isMobile) setOpen(false); }, [isMobile]);

  // mobile: hide the navbar when scrolling down, reveal it again on scroll up
  React.useEffect(() => {
    if (!isMobile) { setHidden(false); return; }
    let lastY = window.scrollY;
    const onScroll = () => {
      const y = window.scrollY;
      const goingDown = y > lastY;
      const next = goingDown && y > 80;
      setHidden(next);
      if (next) setOpen(false);
      lastY = y;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [isMobile]);

  const links = [
    { href: '#screens', label: 'Screens' },
    { href: '#build', label: 'Build' },
    { href: '#control', label: 'Control' },
    { href: '#fuel', label: 'Fuel' },
    { href: '#strength', label: 'Strength' },
  ];

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(236,232,220,0.82)', backdropFilter: 'blur(12px)',
      borderBottom: `1px solid ${L.rule}`,
      transform: hidden ? 'translateY(-100%)' : 'translateY(0)',
      transition: 'transform .25s ease',
    }}>
      <div style={{
        maxWidth: 1200, margin: '0 auto', padding: isMobile ? '14px 20px' : '16px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24,
      }}>
        <Wordmark size={24} />
        {isMobile ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <GetBetaForm />
            <button
              onClick={() => setOpen((o) => !o)}
              aria-label="Menu" aria-expanded={open}
              style={{
                width: 40, height: 40, borderRadius: 12, border: `1px solid ${L.rule}`,
                background: L.card, color: L.ink, display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: 'pointer', flex: '0 0 auto', padding: 0,
              }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                {open ? <path d="M6 6l12 12M18 6L6 18" /> : <path d="M3 6h18M3 12h18M3 18h18" />}
              </svg>
            </button>
          </div>
        ) : (
          <>
            <nav style={{ display: 'flex', gap: 30 }}>
              {links.map((l) => <a key={l.href} href={l.href} style={link}>{l.label}</a>)}
            </nav>
            <GetBetaForm />
          </>
        )}
      </div>
      {isMobile && open && (
        <nav style={{ display: 'flex', flexDirection: 'column', padding: '4px 20px 16px', borderTop: `1px solid ${L.rule}` }}>
          {links.map((l) => (
            <a key={l.href} href={l.href} onClick={() => setOpen(false)} style={{ ...link, fontSize: 15, padding: '12px 0', borderBottom: `1px solid ${L.rule}` }}>{l.label}</a>
          ))}
        </nav>
      )}
    </header>
  );
}

// ── Hero (identity) ───────────────────────────────────
function Hero() {
  const isMobile = useIsMobile(760);

  if (isMobile) {
    return (
      <section style={{ position: 'relative', background: L.bg, overflow: 'hidden', padding: '28px 22px 48px' }}>
        <h1 style={{
          fontFamily: L.display, fontWeight: 800, textAlign: 'center',
          lineHeight: 0.95, letterSpacing: '-0.05em', color: L.ink, margin: 0,
        }}>
          <span style={{ display: 'block', fontSize: 'clamp(36px, 11.3vw, 49px)', whiteSpace: 'nowrap' }}>A Mirror of Who</span>
          <span style={{ display: 'block', fontSize: 'clamp(50px, 13.1vw, 80px)', letterSpacing: '-0.065em', whiteSpace: 'nowrap' }}>
            <span style={{ position: 'relative', zIndex: 0 }}>
                You're Becoming
              <span style={{
                position: 'absolute', left: '-2%', right: '-2%', bottom: '0.05em', height: '0.5em',
                background: L.hype, borderRadius: 3, zIndex: -1,
              }} />
            </span>
          </span>
        </h1>

        <p style={{
          fontFamily: L.body, fontSize: 18, lineHeight: 1.5, color: L.ink2, textAlign: 'center',
          margin: '16px 0 0', textWrap: 'pretty',
        }}>
          Become conscious of your small decisions and where they're leading you.
        </p>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
          marginTop: 20, fontFamily: L.mono, fontSize: 11, color: L.ink3, letterSpacing: '0.03em',
        }}>
          {/* <span>iPhone</span>
          <span style={{ width: 3, height: 3, borderRadius: '50%', background: L.ink3 }} />
          <span>Apple Health sync</span>
          <span style={{ width: 3, height: 3, borderRadius: '50%', background: L.ink3 }} />
          <span>Free to start</span> */}
        </div>

        {/* app preview rising from the fold */}
        <div style={{ position: 'relative', marginTop: 30, display: 'flex', justifyContent: 'center' }}>
          {/* soft lime halo */}
          <div style={{
            position: 'absolute', top: 30, left: '50%', transform: 'translateX(-50%)',
            width: 360, height: 360, borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(184,242,58,0.45), rgba(184,242,58,0) 68%)',
            filter: 'blur(8px)', pointerEvents: 'none',
          }} />
          <div style={{ filter: 'drop-shadow(0 36px 50px rgba(20,17,13,0.26))', position: 'relative' }}>
            <PhoneShot scale={0.84} clip={874 * 0.7}><A_Becoming state="improving" /></PhoneShot>
            {/* fade the bottom of the phone into the dark problem section */}
            <div style={{
              position: 'absolute', left: 0, right: 0, bottom: 0, height: 120,
              background: `linear-gradient(180deg, rgba(236,232,220,0), ${L.ink})`,
              pointerEvents: 'none',
            }} />
          </div>
        </div>
      </section>
    );
  }

  return (
    <section style={{
      maxWidth: 1200, margin: '0 auto',
      padding: '48px 32px 56px',
      minHeight: 'calc(100vh - 69px)',
      display: 'grid', gridTemplateColumns: '1.15fr 0.85fr', gap: 48, alignItems: 'center',
    }} className="hero-grid">
      <div style={{ textAlign: 'left' }}>
        <h1 style={{
          fontFamily: L.display, fontWeight: 800, fontSize: 'clamp(52px, 7.2vw, 92px)',
          lineHeight: 0.93, letterSpacing: '-0.04em', color: L.ink, margin: 0,
        }}>
          <span style={{ display: 'block', fontSize: '0.7em', whiteSpace: 'nowrap' }}>A Mirror of Who</span>
          <span style={{ display: 'block', whiteSpace: 'nowrap' }}>
            <span style={{ position: 'relative', zIndex: 0 }}>
              You're Becoming
              <span style={{
                position: 'absolute', left: '-2%', right: '-2%', bottom: '0.09em', height: '0.5em',
                background: L.hype, borderRadius: 3, zIndex: -1,
              }} />
            </span>
          </span>
        </h1>

        <p style={{
          fontFamily: L.body, fontSize: 19, lineHeight: 1.5, color: L.ink2,
          margin: '24px 0 0', maxWidth: 470, textWrap: 'pretty',
        }}>
          Become conscious of your small decisions and where they're leading you.
        </p>

        <div style={{ display: 'flex', gap: 12, marginTop: 32, flexWrap: 'wrap' }}>
          <Btn kind="solid" big>Get grittt — free</Btn>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 20 }}>
        <div style={{ filter: 'drop-shadow(0 50px 70px rgba(20,17,13,0.22))' }}>
          <PhoneShot scale={0.605}><A_Becoming state="improving" /></PhoneShot>
        </div>
        <div style={{ filter: 'drop-shadow(0 50px 70px rgba(20,17,13,0.22))' }}>
          <PhoneShot scale={0.605}><A_Dashboard name="CHRIS" mirrorState="improving" /></PhoneShot>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { L, PhoneShot, Wordmark, Btn, Eyebrow, RoundArrow, GetBetaForm, Nav, Hero, useIsMobile });
