// Shared tokens, hooks, logo, nav and footer for Gregis.
// Loaded on every page; page-specific components live in /pages/*.jsx.

const GREGIS_BLUE = '#1d3df5';
const GREGIS_INK = '#0a0f2a';
const GREGIS_BG = '#ffffff';
const GREGIS_MUTED = '#54596f';
const GREGIS_LINE = '#e6e9f2';
const GREGIS_LINE_SOFT = '#f1f2f7';

const FONT_SERIF = "'Source Serif 4', 'Source Serif Pro', Charter, Georgia, serif";
const FONT_SERIF_ITALIC = "'Instrument Serif', 'Source Serif 4', Georgia, serif";
const FONT_SANS = "'Geist', -apple-system, system-ui, 'Inter', sans-serif";
const FONT_MONO = "'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace";

// Contact / scheduling
const GREGIS_CONTACT = {
  email: 'gabriel@gregis.ai',
  durationMinutes: 20,
  appointmentUrl: 'https://calendar.app.google/td3Z7TABVcJroig3A',
  calendarEmbedUrl:
    'https://calendar.google.com/calendar/appointments/schedules/AcZssZ0hwYAOi-uJRULaTmXtpDKQg1-WG1gs1tvn1SGSY2Z6jb1MJTQ6A6PnTNnvqE-j-gn4o9iH7GO6',
};

const NAV_ITEMS = [
  { label: 'Home', href: '/', key: 'home' },
  { label: 'For Operators', href: '/operators/', key: 'operators' },
  { label: 'For Underwriters', href: '/underwriters/', key: 'underwriters' },
  { label: 'For Enterprises', href: '/enterprises/', key: 'enterprises' },
  { label: 'Approach', href: '/approach/', key: 'approach' },
  { label: 'Company', href: '/company/', key: 'company' },
  { label: 'Contact', href: '/contact/', key: 'contact' },
];

function useInView(opts = { threshold: 0.2, once: true }) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    const io = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setInView(true);
          if (opts.once) io.disconnect();
        } else if (!opts.once) {
          setInView(false);
        }
      },
      { threshold: opts.threshold ?? 0.2 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, inView];
}

function useMediaQuery(query) {
  const get = () =>
    typeof window === 'undefined' || !window.matchMedia ? false : window.matchMedia(query).matches;
  const [matches, setMatches] = React.useState(get);
  React.useEffect(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return;
    const m = window.matchMedia(query);
    const on = () => setMatches(m.matches);
    on();
    if (m.addEventListener) {
      m.addEventListener('change', on);
      return () => m.removeEventListener('change', on);
    }
    m.addListener(on);
    return () => m.removeListener(on);
  }, [query]);
  return matches;
}

// Sierpinski-mark wordmark used in the nav and hero corner. Kept as-is.
function GregisLogo({ width = 180, color }) {
  const blue = color || GREGIS_BLUE;
  const top = { x: 260, y: 110 };
  const left = { x: 105, y: 380 };
  const right = { x: 415, y: 380 };

  const midpoint = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
  const sierpinski = (a, b, c, depth) => {
    if (depth === 0) return [[a, b, c]];
    const ab = midpoint(a, b);
    const bc = midpoint(b, c);
    const ca = midpoint(c, a);
    return [
      ...sierpinski(a, ab, ca, depth - 1),
      ...sierpinski(ab, b, bc, depth - 1),
      ...sierpinski(ca, bc, c, depth - 1),
    ];
  };
  const tri = sierpinski(top, left, right, 2);

  return (
    <svg
      width={width}
      viewBox="0 0 950 500"
      xmlns="http://www.w3.org/2000/svg"
      role="img"
      aria-label="Gregis"
    >
      <g fill={blue}>
        {tri.map((pts, i) => (
          <polygon key={i} points={pts.map((p) => `${p.x},${p.y}`).join(' ')} />
        ))}
      </g>
      <text
        x="505"
        y="315"
        fill={blue}
        fontSize="135"
        fontFamily="Inter, Helvetica, Arial, sans-serif"
        fontWeight="700"
        letterSpacing="-8"
      >
        gregis
      </text>
    </svg>
  );
}

// Small caps mono eyebrow used to label sections.
function Eyebrow({ children, color }) {
  return (
    <div
      style={{
        fontFamily: FONT_MONO,
        fontSize: 11,
        letterSpacing: '0.18em',
        textTransform: 'uppercase',
        color: color || GREGIS_BLUE,
        marginBottom: 16,
      }}
    >
      {children}
    </div>
  );
}

// Section wrapper with consistent gutter and max-width.
function Section({ children, id, background, color, narrow, style }) {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const reduced = useMediaQuery('(prefers-reduced-motion: reduce)');
  const [ref, inView] = useInView({ threshold: 0.12, once: true });
  const reveal = !reduced;
  return (
    <section
      id={id}
      style={{
        background: background || 'transparent',
        color: color || 'inherit',
        padding: isMobile ? '64px 22px' : '104px 56px',
        borderTop: `1px solid ${GREGIS_LINE}`,
        ...(style || {}),
      }}
    >
      <div
        ref={ref}
        style={{
          maxWidth: narrow ? 820 : 1120,
          margin: '0 auto',
          opacity: reveal && !inView ? 0 : 1,
          transform: reveal && !inView ? 'translateY(14px)' : 'none',
          transition: reveal ? 'opacity 640ms ease, transform 640ms ease' : 'none',
          willChange: reveal ? 'opacity, transform' : undefined,
        }}
      >
        {children}
      </div>
    </section>
  );
}

function PrimaryLink({ href, children, target }) {
  return (
    <a
      href={href}
      target={target}
      rel={target === '_blank' ? 'noreferrer' : undefined}
      className="gregis-cta gregis-cta-primary"
      style={{
        display: 'inline-block',
        background: GREGIS_INK,
        color: '#fff',
        padding: '14px 22px',
        textDecoration: 'none',
        fontFamily: FONT_MONO,
        fontSize: 12,
        letterSpacing: '0.05em',
        borderRadius: 2,
      }}
    >
      {children}
    </a>
  );
}

function SecondaryLink({ href, children, target }) {
  return (
    <a
      href={href}
      target={target}
      rel={target === '_blank' ? 'noreferrer' : undefined}
      className="gregis-cta gregis-cta-secondary"
      style={{
        display: 'inline-block',
        background: 'transparent',
        color: GREGIS_INK,
        padding: '14px 22px',
        textDecoration: 'none',
        fontFamily: FONT_MONO,
        fontSize: 12,
        letterSpacing: '0.05em',
        borderRadius: 2,
        border: `1px solid ${GREGIS_INK}`,
      }}
    >
      {children}
    </a>
  );
}

function Nav({ active }) {
  const isMobile = useMediaQuery('(max-width: 860px)');
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    if (typeof window === 'undefined') return undefined;
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav
      style={{
        position: 'sticky',
        top: 0,
        zIndex: 50,
        background: scrolled ? 'rgba(255,255,255,0.86)' : 'rgba(255,255,255,0.6)',
        backdropFilter: 'saturate(140%) blur(14px)',
        WebkitBackdropFilter: 'saturate(140%) blur(14px)',
        borderBottom: `1px solid ${scrolled ? GREGIS_LINE : 'transparent'}`,
        boxShadow: scrolled ? '0 1px 0 rgba(10,15,42,0.04)' : 'none',
        transition: 'background-color 220ms ease, border-color 220ms ease, box-shadow 220ms ease',
      }}
    >
      <div
        style={{
          maxWidth: 1320,
          margin: '0 auto',
          padding: isMobile ? '14px 18px' : '18px 56px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 24,
        }}
      >
        <a
          href="/"
          aria-label="Gregis home"
          style={{ display: 'inline-flex', textDecoration: 'none' }}
        >
          <GregisLogo width={isMobile ? 112 : 140} />
        </a>

        {isMobile ? (
          <button
            type="button"
            onClick={() => setOpen((v) => !v)}
            aria-label="Toggle navigation"
            aria-expanded={open}
            style={{
              background: 'transparent',
              border: `1px solid ${GREGIS_LINE}`,
              color: GREGIS_INK,
              fontFamily: FONT_MONO,
              fontSize: 11,
              letterSpacing: '0.12em',
              padding: '8px 12px',
              borderRadius: 2,
              cursor: 'pointer',
            }}
          >
            {open ? 'CLOSE' : 'MENU'}
          </button>
        ) : (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 28,
              fontFamily: FONT_SANS,
              fontSize: 14,
            }}
          >
            {NAV_ITEMS.slice(1).map((item) => (
              <a
                key={item.key}
                href={item.href}
                className="gregis-nav-link"
                style={{
                  color: active === item.key ? GREGIS_INK : GREGIS_MUTED,
                  textDecoration: 'none',
                  fontWeight: active === item.key ? 500 : 400,
                  paddingBottom: 2,
                  borderBottom: active === item.key ? `1px solid ${GREGIS_INK}` : '1px solid transparent',
                }}
              >
                {item.label}
              </a>
            ))}
          </div>
        )}
      </div>

      {isMobile && open && (
        <div
          style={{
            borderTop: `1px solid ${GREGIS_LINE}`,
            padding: '8px 18px 16px',
            display: 'flex',
            flexDirection: 'column',
            gap: 4,
            fontFamily: FONT_SANS,
            fontSize: 15,
          }}
        >
          {NAV_ITEMS.slice(1).map((item) => (
            <a
              key={item.key}
              href={item.href}
              className="gregis-nav-link"
              style={{
                color: active === item.key ? GREGIS_INK : GREGIS_MUTED,
                textDecoration: 'none',
                fontWeight: active === item.key ? 500 : 400,
                padding: '10px 0',
                borderBottom: `1px solid ${GREGIS_LINE_SOFT}`,
              }}
            >
              {item.label}
            </a>
          ))}
        </div>
      )}
    </nav>
  );
}

function Footer() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  return (
    <footer
      style={{
        background: GREGIS_INK,
        color: '#fff',
        padding: isMobile ? '64px 22px 36px' : '96px 56px 48px',
      }}
    >
      <div style={{ maxWidth: 1120, margin: '0 auto' }}>
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: isMobile ? '1fr' : '1.2fr 1fr',
            gap: isMobile ? 28 : 48,
            alignItems: 'start',
          }}
        >
          <div>
            <Eyebrow color="rgba(255,255,255,0.72)">Contact</Eyebrow>
            <h2
              style={{
                fontFamily: FONT_SERIF,
                fontWeight: 500,
                fontSize: isMobile ? 32 : 44,
                lineHeight: 1.08,
                letterSpacing: '-0.01em',
                margin: '0 0 16px',
              }}
            >
              Start a conversation.
            </h2>
            <p
              style={{
                fontSize: 15,
                lineHeight: 1.6,
                color: 'rgba(255,255,255,0.74)',
                margin: '0 0 24px',
                maxWidth: 480,
              }}
            >
              Engagements start with a conversation. Reach out and we will find the right fit for your situation.
            </p>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
              <a
                href="/contact/"
                style={{
                  display: 'inline-block',
                  background: '#fff',
                  color: GREGIS_INK,
                  padding: '14px 22px',
                  textDecoration: 'none',
                  fontFamily: FONT_MONO,
                  fontSize: 12,
                  letterSpacing: '0.05em',
                  borderRadius: 2,
                }}
              >
                Contact us
              </a>
            </div>
          </div>

          <div
            style={{
              display: 'grid',
              gridTemplateColumns: '1fr 1fr',
              gap: 24,
              fontFamily: FONT_SANS,
              fontSize: 14,
              color: 'rgba(255,255,255,0.72)',
            }}
          >
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <span
                style={{
                  fontFamily: FONT_MONO,
                  fontSize: 11,
                  letterSpacing: '0.18em',
                  textTransform: 'uppercase',
                  color: 'rgba(255,255,255,0.72)',
                  marginBottom: 4,
                }}
              >
                Audiences
              </span>
              <a href="/underwriters/" style={{ color: '#fff', textDecoration: 'none' }}>
                For Underwriters
              </a>
              <a href="/enterprises/" style={{ color: '#fff', textDecoration: 'none' }}>
                For Enterprises
              </a>
              <a href="/operators/" style={{ color: '#fff', textDecoration: 'none' }}>
                For Operators
              </a>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <span
                style={{
                  fontFamily: FONT_MONO,
                  fontSize: 11,
                  letterSpacing: '0.18em',
                  textTransform: 'uppercase',
                  color: 'rgba(255,255,255,0.72)',
                  marginBottom: 4,
                }}
              >
                More
              </span>
              <a href="/approach/" style={{ color: '#fff', textDecoration: 'none' }}>
                Approach
              </a>
              <a href="/company/" style={{ color: '#fff', textDecoration: 'none' }}>
                Company
              </a>
              <a href="/contact/" style={{ color: '#fff', textDecoration: 'none' }}>
                Contact
              </a>
            </div>
          </div>
        </div>

        <div
          style={{
            marginTop: isMobile ? 48 : 80,
            paddingTop: 20,
            borderTop: '1px solid rgba(255,255,255,0.16)',
            display: 'flex',
            flexDirection: isMobile ? 'column' : 'row',
            gap: 8,
            justifyContent: 'space-between',
            fontFamily: FONT_MONO,
            fontSize: 11,
            letterSpacing: '0.1em',
            color: 'rgba(255,255,255,0.6)',
          }}
        >
          <span>GREGIS · gregis.ai</span>
          <span>© {new Date().getFullYear()}</span>
        </div>
      </div>
    </footer>
  );
}

const GREGIS_GLOBAL_CSS = `
.gregis-nav-link { transition: color 180ms ease, border-color 180ms ease; }
.gregis-nav-link:hover { color: ${GREGIS_INK} !important; border-bottom-color: ${GREGIS_INK} !important; }

.gregis-cta { transition: background-color 200ms ease, color 200ms ease, border-color 200ms ease, transform 200ms ease, box-shadow 200ms ease; }
.gregis-cta:hover { transform: translateY(-1px); box-shadow: 0 10px 22px rgba(10,15,42,0.16); }
.gregis-cta-primary:hover { background: ${GREGIS_BLUE} !important; }
.gregis-cta-secondary:hover { background: ${GREGIS_INK} !important; color: #fff !important; border-color: ${GREGIS_INK} !important; }

@media (prefers-reduced-motion: reduce) {
  .gregis-nav-link, .gregis-cta { transition: none !important; }
  .gregis-cta:hover { transform: none !important; box-shadow: none !important; }
}
`;

function GlobalStyles() {
  return <style dangerouslySetInnerHTML={{ __html: GREGIS_GLOBAL_CSS }} />;
}

// Page shell — every page wraps content in this so nav/footer stay consistent.
function PageShell({ active, children }) {
  return (
    <div
      style={{
        background: GREGIS_BG,
        color: GREGIS_INK,
        fontFamily: FONT_SANS,
        minHeight: '100vh',
      }}
    >
      <GlobalStyles />
      <Nav active={active} />
      <main>{children}</main>
      <Footer />
    </div>
  );
}

function CalendarWidget({ compact = false }) {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const baseUrl = GREGIS_CONTACT.calendarEmbedUrl || GREGIS_CONTACT.appointmentUrl;
  const src = baseUrl.includes('?') ? `${baseUrl}&gv=true` : `${baseUrl}?gv=true`;
  const height = isMobile ? 760 : compact ? 680 : 720;

  return (
    <div style={{ minWidth: 0, maxWidth: '100%' }}>
      <div
        style={{
          background: '#fff',
          border: `1px solid ${GREGIS_LINE}`,
          borderRadius: 2,
          overflow: 'hidden',
          boxShadow: '0 18px 48px rgba(10,15,42,0.16)',
        }}
      >
        <iframe
          src={src}
          title="Schedule a call with Gregis"
          width="100%"
          height={height}
          frameBorder="0"
          loading="lazy"
          style={{ border: 0, display: 'block', width: '100%', height }}
        />
        <div
          style={{
            display: 'flex',
            flexWrap: 'wrap',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 12,
            padding: '12px 18px',
            borderTop: `1px solid ${GREGIS_LINE_SOFT}`,
            background: '#fff',
            fontFamily: FONT_MONO,
            fontSize: 11,
            letterSpacing: '0.12em',
            textTransform: 'uppercase',
            color: GREGIS_MUTED,
          }}
        >
          <span>{GREGIS_CONTACT.durationMinutes}-min intro call · Google Calendar</span>
          <a
            href={GREGIS_CONTACT.appointmentUrl}
            target="_blank"
            rel="noreferrer"
            style={{ color: GREGIS_BLUE, textDecoration: 'none' }}
          >
            Open in new tab →
          </a>
        </div>
      </div>
    </div>
  );
}

// Form atoms

function FormLabel({ children, required }) {
  return (
    <label
      style={{
        display: 'block',
        fontFamily: FONT_MONO,
        fontSize: 11,
        letterSpacing: '0.12em',
        textTransform: 'uppercase',
        color: GREGIS_MUTED,
        marginBottom: 8,
      }}
    >
      {children}
      {required ? (
        <span style={{ color: GREGIS_BLUE, marginLeft: 6 }}>*</span>
      ) : (
        <span style={{ marginLeft: 6, opacity: 0.6 }}>(optional)</span>
      )}
    </label>
  );
}

const inputBase = {
  display: 'block',
  width: '100%',
  padding: '12px 14px',
  border: `1px solid ${GREGIS_LINE}`,
  borderRadius: 2,
  background: '#fff',
  color: GREGIS_INK,
  fontFamily: FONT_SANS,
  fontSize: 15,
  lineHeight: 1.4,
  outline: 'none',
};

function TextInput(props) {
  return <input {...props} style={{ ...inputBase, ...(props.style || {}) }} />;
}

function TextArea(props) {
  return (
    <textarea
      {...props}
      rows={props.rows || 4}
      style={{ ...inputBase, resize: 'vertical', minHeight: 110, ...(props.style || {}) }}
    />
  );
}

function SelectInput({ children, ...props }) {
  return (
    <select {...props} style={{ ...inputBase, ...(props.style || {}) }}>
      {children}
    </select>
  );
}

// Build a mailto: link from form data. Fallback while no backend is wired up.
// TODO: replace with POST to /api/contact (Formspree, Web3Forms, or custom backend).
function submitViaMailto({ subject, fields }) {
  const lines = Object.entries(fields)
    .filter(([, v]) => v !== undefined && v !== null && String(v).length > 0)
    .map(([k, v]) => `${k}: ${v}`);
  const body = lines.join('\n');
  const url = `mailto:${GREGIS_CONTACT.email}?subject=${encodeURIComponent(
    subject
  )}&body=${encodeURIComponent(body)}`;
  window.location.href = url;
}

Object.assign(window, {
  GREGIS_BLUE,
  GREGIS_INK,
  GREGIS_BG,
  GREGIS_MUTED,
  GREGIS_LINE,
  GREGIS_LINE_SOFT,
  FONT_SERIF,
  FONT_SERIF_ITALIC,
  FONT_SANS,
  FONT_MONO,
  GREGIS_CONTACT,
  NAV_ITEMS,
  useInView,
  useMediaQuery,
  GregisLogo,
  Eyebrow,
  Section,
  PrimaryLink,
  SecondaryLink,
  Nav,
  Footer,
  PageShell,
  CalendarWidget,
  FormLabel,
  TextInput,
  TextArea,
  SelectInput,
  submitViaMailto,
});
