'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import Image from 'next/image';

const INK = '#0a0a0a';

const NAV_LINKS = [
  { label: 'Earn', href: '#for-you', color: '#C8FF37' },   // lime
  { label: 'Spend', href: '#difference', color: '#FF2E88' }, // pink
  { label: 'Live', href: '#the-vision', color: '#8B3DFF' },  // purple
];

const MOBILE_QUERY = '(max-width: 1023px)';

export default function Header() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [hidden, setHidden] = useState(false);
  const mobileMenuRef = useRef<HTMLDivElement>(null);
  const lastScrollYRef = useRef(0);

  // Hide on scroll-down, reveal on scroll-up; deepen the shadow once scrolled.
  useEffect(() => {
    lastScrollYRef.current = window.scrollY;
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 40);
      const lastY = lastScrollYRef.current;
      if (y <= 80) setHidden(false);
      else if (y > lastY + 4) setHidden(true);
      else if (y < lastY - 4) setHidden(false);
      lastScrollYRef.current = y;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (mobileOpen) setHidden(false);
  }, [mobileOpen]);

  useEffect(() => {
    if (!mobileOpen) return;
    const handler = (e: MouseEvent) => {
      if (mobileMenuRef.current && !mobileMenuRef.current.contains(e.target as Node)) {
        setMobileOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [mobileOpen]);

  useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  const [isMobileViewport, setIsMobileViewport] = useState(false);
  useEffect(() => {
    const mql = window.matchMedia(MOBILE_QUERY);
    setIsMobileViewport(mql.matches);
    const update = () => setIsMobileViewport(mql.matches);
    mql.addEventListener('change', update);
    return () => mql.removeEventListener('change', update);
  }, []);

  return (
    <div suppressHydrationWarning>
      {/* Mobile menu overlay */}
      {mobileOpen && (
        <div
          onClick={() => setMobileOpen(false)}
          aria-hidden="true"
          style={{ position: 'fixed', inset: 0, zIndex: 99999998, background: 'rgba(10,4,20,0.6)' }}
        />
      )}

      {/* Mobile slide-in panel — night dot-grid, neobrutalist links */}
      <div
        ref={mobileMenuRef}
        role="dialog"
        aria-label="Navigation menu"
        aria-modal="true"
        className="bg-night"
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          height: '100%',
          width: 'min(330px, 86vw)',
          zIndex: 999999999,
          color: '#fff',
          transform: mobileOpen ? 'translateX(0)' : 'translateX(-100%)',
          transition: 'transform 0.32s cubic-bezier(0.34,1.3,0.64,1)',
          overflowY: 'auto',
          padding: '22px 24px 40px',
          display: 'flex',
          flexDirection: 'column',
          gap: '28px',
          // Border + shadow only while open, so nothing bleeds onto the screen's
          // left edge when the panel is parked off-screen.
          borderRight: mobileOpen ? `4px solid ${INK}` : 'none',
          boxShadow: mobileOpen ? `8px 0 0 0 rgba(0,0,0,0.35)` : 'none',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ display: 'inline-flex', background: '#fff', border: `3px solid ${INK}`, borderRadius: 14, padding: '8px 12px', boxShadow: `4px 4px 0 0 ${INK}` }}>
            <Image src="/images/lytsup_app.png" alt="LytsUp" width={2048} height={554} priority style={{ height: 24, width: 'auto', display: 'block' }} />
          </span>
          <button
            onClick={() => setMobileOpen(false)}
            aria-label="Close menu"
            style={{ background: '#FF2E88', color: '#fff', border: `3px solid ${INK}`, borderRadius: 12, width: 40, height: 40, fontSize: 20, fontWeight: 900, cursor: 'pointer', lineHeight: 1, boxShadow: `3px 3px 0 0 ${INK}` }}
          >
            ✕
          </button>
        </div>

        <nav>
          <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: '12px' }}>
            {NAV_LINKS.map(({ label, href, color }) => (
              <li key={href}>
                <Link
                  href={href}
                  onClick={() => setMobileOpen(false)}
                  className="font-sora"
                  style={{
                    display: 'block',
                    padding: '14px 18px',
                    color: INK,
                    background: color,
                    textDecoration: 'none',
                    fontSize: '18px',
                    fontWeight: 800,
                    textTransform: 'uppercase',
                    letterSpacing: '0.02em',
                    border: `3px solid ${INK}`,
                    borderRadius: 14,
                    boxShadow: `4px 4px 0 0 ${INK}`,
                  }}
                >
                  {label}
                </Link>
              </li>
            ))}
          </ul>
        </nav>

        <div>
          <p className="font-sora" style={{ margin: '0 0 12px', fontWeight: 800, textTransform: 'uppercase', fontSize: '11px', letterSpacing: '0.12em', color: '#FFC72C' }}>
            Follow us
          </p>
          <div style={{ display: 'flex', gap: '12px' }}>
            {SOCIALS.map(({ href, label, icon }) => (
              <a
                key={label}
                href={href}
                target="_blank"
                rel="noopener noreferrer"
                aria-label={label}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 40, height: 40, borderRadius: 12, background: '#fff', color: INK, border: `3px solid ${INK}`, boxShadow: `3px 3px 0 0 ${INK}` }}
              >
                {icon}
              </a>
            ))}
          </div>
        </div>

        <Link
          href="#for-business"
          onClick={() => setMobileOpen(false)}
          className="font-sora"
          style={{
            display: 'block',
            marginTop: 'auto',
            padding: '16px 24px',
            background: '#FFC72C',
            color: INK,
            border: `3px solid ${INK}`,
            borderRadius: 14,
            fontWeight: 900,
            fontSize: 16,
            textTransform: 'uppercase',
            textDecoration: 'none',
            textAlign: 'center',
            boxShadow: `5px 5px 0 0 ${INK}`,
          }}
        >
          Get Started →
        </Link>
      </div>

      {/* ——— Funky neobrutalist floating bar ——— */}
      <header
        style={{
          position: 'fixed',
          top: isMobileViewport ? '14px' : '18px',
          left: 0,
          right: 0,
          width: isMobileViewport ? 'auto' : '70%',
          maxWidth: 'calc(100% - 2 * var(--hdr-gutter))',
          marginLeft: isMobileViewport ? 'var(--hdr-gutter)' : 'auto',
          marginRight: isMobileViewport ? 'var(--hdr-gutter)' : 'auto',
          zIndex: 99999999,
          background: '#FFFDF5',
          border: `3px solid ${INK}`,
          borderRadius: '20px',
          boxShadow: scrolled ? `8px 8px 0 0 ${INK}` : `5px 6px 0 0 ${INK}`,
          transform: hidden ? 'translateY(-160%)' : 'translateY(0)',
          transition: 'transform 0.35s cubic-bezier(0.4,0,0.2,1), box-shadow 0.25s ease',
        }}
      >
        <div className="header-inner" style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '0 22px',
          height: '72px',
          width: '100%',
          boxSizing: 'border-box',
          gap: 16,
        }}>
          {/* Logo */}
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Link href="#intro" aria-label="LytsUp home" style={{ display: 'inline-flex', alignItems: 'center', textDecoration: 'none' }}>
              <Image
                src="/images/lytsup_app.png"
                alt="LytsUp"
                width={2048}
                height={554}
                priority
                className="header-logo-img"
                style={{ height: 34, width: 'auto', objectFit: 'contain', display: 'block' }}
              />
            </Link>
          </div>

          {/* Desktop nav — boxy neobrutalist sticker tabs */}
          <nav aria-label="Main navigation" className="desktop-nav">
            <ul className="header-nav-row" style={{
              display: 'flex',
              listStyle: 'none',
              margin: 0,
              padding: 0,
              alignItems: 'center',
              gap: 12,
            }}>
              {NAV_LINKS.map(({ label, href, color }, i) => {
                const tilt = i % 2 === 0 ? -2 : 2;
                return (
                  <li key={href}>
                    <Link
                      href={href}
                      className="header-nav-tab font-sora"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: 8,
                        padding: '8px 16px',
                        color: INK,
                        textDecoration: 'none',
                        fontWeight: 800,
                        fontSize: '13px',
                        letterSpacing: '0.05em',
                        textTransform: 'uppercase',
                        borderRadius: '12px',
                        background: '#fff',
                        border: `2.5px solid ${INK}`,
                        boxShadow: `3px 3px 0 0 ${INK}`,
                        transition: 'transform 0.15s, background 0.15s, box-shadow 0.15s',
                        whiteSpace: 'nowrap',
                        transform: `rotate(${tilt}deg)`,
                        ['--hov' as string]: color,
                        ['--tilt' as string]: `${tilt}deg`,
                      }}
                    >
                      <span
                        style={{ width: 8, height: 8, borderRadius: 3, background: color, border: `1.5px solid ${INK}`, flexShrink: 0 }}
                      />
                      {label}
                    </Link>
                  </li>
                );
              })}
            </ul>
          </nav>

          {/* Right actions */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Link
              href="#for-business"
              className="header-cta desktop-nav font-sora"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                padding: '11px 26px',
                background: '#FFC72C',
                color: INK,
                border: `3px solid ${INK}`,
                borderRadius: '50px',
                fontWeight: 900,
                textDecoration: 'none',
                fontSize: '14px',
                textTransform: 'uppercase',
                letterSpacing: '0.03em',
                whiteSpace: 'nowrap',
                boxShadow: `3px 3px 0 0 ${INK}`,
                transition: 'transform 0.12s ease, box-shadow 0.12s ease, background 0.15s',
              }}
            >
              Get Started
            </Link>

            {/* Hamburger — mobile only */}
            <button
              className="menu-trigger"
              onClick={() => setMobileOpen(true)}
              aria-label="Open navigation menu"
              aria-expanded={mobileOpen}
              style={{ background: '#8B3DFF', border: `3px solid ${INK}`, borderRadius: 12, cursor: 'pointer', padding: 0, width: 44, height: 44, display: 'none', alignItems: 'center', justifyContent: 'center', boxShadow: `3px 3px 0 0 ${INK}` }}
            >
              <span style={{ display: 'flex', flexDirection: 'column', gap: '4px', width: '20px' }}>
                <span style={{ display: 'block', height: '3px', background: '#fff', borderRadius: '2px' }} />
                <span style={{ display: 'block', height: '3px', background: '#fff', borderRadius: '2px' }} />
                <span style={{ display: 'block', height: '3px', background: '#fff', borderRadius: '2px' }} />
              </span>
            </button>
          </div>
        </div>
      </header>

      <style>{`
        @media (max-width: 1023px) {
          .desktop-nav { display: none !important; }
          .menu-trigger { display: flex !important; }
          .header-inner { height: 60px !important; }
          .header-logo-img { height: 28px !important; }
        }
        @media (min-width: 1024px) and (max-width: 1200px) {
          .header-nav-tab { padding: 7px 12px !important; font-size: 11px !important; letter-spacing: 0.03em !important; }
          .header-cta { padding: 9px 18px !important; font-size: 12px !important; }
          .header-logo-img { height: 30px !important; }
        }
        .header-nav-tab:hover {
          background: var(--hov) !important;
          transform: translateY(-3px) rotate(var(--tilt));
          box-shadow: 5px 5px 0 0 ${INK} !important;
        }
        .header-nav-tab:active {
          transform: translateY(1px) rotate(var(--tilt));
          box-shadow: 1px 1px 0 0 ${INK} !important;
        }
        .header-cta:hover {
          background: #FFD95A !important;
          transform: translate(-2px, -2px);
          box-shadow: 5px 5px 0 0 ${INK} !important;
        }
        .header-cta:active {
          transform: translate(1px, 1px);
          box-shadow: 1px 1px 0 0 ${INK} !important;
        }
      `}</style>
    </div>
  );
}

/* ——— Inline SVG social icons ——— */
const SOCIALS = [
  {
    label: 'Instagram', href: 'https://instagram.com/lytsup',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2.16c3.2 0 3.58.01 4.85.07 3.25.15 4.77 1.69 4.92 4.92.06 1.27.07 1.65.07 4.85 0 3.2-.01 3.58-.07 4.85-.15 3.23-1.66 4.77-4.92 4.92-1.27.06-1.64.07-4.85.07-3.2 0-3.58-.01-4.85-.07-3.26-.15-4.77-1.7-4.92-4.92-.06-1.27-.07-1.64-.07-4.85 0-3.2.01-3.58.07-4.85.15-3.23 1.66-4.77 4.92-4.92C8.42 2.17 8.8 2.16 12 2.16zm0-2.16C8.74 0 8.33.01 7.05.07 2.7.27.27 2.69.07 7.05.01 8.33 0 8.74 0 12s.01 3.67.07 4.95c.2 4.36 2.62 6.78 6.98 6.98C8.33 23.99 8.74 24 12 24s3.67-.01 4.95-.07c4.35-.2 6.78-2.62 6.98-6.98.06-1.28.07-1.69.07-4.95s-.01-3.67-.07-4.95c-.2-4.35-2.62-6.78-6.98-6.98C15.67.01 15.26 0 12 0zm0 5.84a6.16 6.16 0 100 12.32 6.16 6.16 0 000-12.32zM12 16a4 4 0 110-8 4 4 0 010 8zm6.41-11.85a1.44 1.44 0 100 2.88 1.44 1.44 0 000-2.88z"/></svg>,
  },
  {
    label: 'X / Twitter', href: 'https://twitter.com/lytsup',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M13.98 10.62 20.54 3h-1.55l-5.7 6.62L8.74 3H3.5l6.88 10.01L3.5 21h1.55l6.01-6.99L15.87 21h5.24l-7.13-10.38zm-2.13 2.47-.7-1-5.54-7.93H8l4.47 6.4.7 1 5.82 8.32h-2.39l-4.74-6.79z"/></svg>,
  },
  {
    label: 'YouTube', href: 'https://www.youtube.com/@lytsup',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.8 8s-.2-1.38-.8-1.99c-.76-.8-1.61-.8-2-.85C16.2 5 12 5 12 5s-4.2 0-7 .17c-.39.05-1.24.05-2 .85C2.4 6.62 2.2 8 2.2 8S2 9.62 2 11.24v1.52c0 1.62.2 3.24.2 3.24s.2 1.38.8 1.99c.76.8 1.76.77 2.2.85C6.8 19 12 19.03 12 19.03s4.2-.01 7-.22c.39-.05 1.24-.05 2-.85.6-.61.8-1.99.8-1.99S22 14.38 22 12.76v-1.52C22 9.62 21.8 8 21.8 8zm-11.87 6.59V8.79l5.4 2.82-5.4 2.98z"/></svg>,
  },
];
