// Philosophy. Four ideas keyed to the hero rotator: Time -> Wealth -> Scale -> Freedom.
// Scroll-driven single-active illumination: whichever card is closest to the
// viewport center is lit; the rest sit dim. Hover overrides the scroll-pick
// while the cursor is inside the grid.
const Tenet = React.forwardRef(({ n, word, body }, ref) => (
  <div
    ref={ref}
    className="orx-tenet"
    style={{
      position: 'relative',
      padding: '40px 36px',
      borderRadius: 20,
      display: 'flex',
      flexDirection: 'column',
      gap: 20,
      minHeight: 360,
      transition:
        'background 2880ms cubic-bezier(0.22,1,0.36,1), box-shadow 2880ms cubic-bezier(0.22,1,0.36,1), border-color 2880ms cubic-bezier(0.22,1,0.36,1), transform 2880ms cubic-bezier(0.22,1,0.36,1)',
    }}
  >
    <div style={{
      display: 'flex',
      alignItems: 'baseline',
      justifyContent: 'space-between',
      gap: 16,
    }}>
      <div className="orx-tenet__num" style={{
        fontFamily: "'Inter Tight', sans-serif",
        fontSize: 11,
        letterSpacing: '0.22em',
        textTransform: 'uppercase',
        fontWeight: 500,
        transition: 'color 2880ms cubic-bezier(0.22,1,0.36,1)',
      }}>{n}</div>
      <div className="orx-tenet__verb" style={{
        fontFamily: "'Inter Tight', sans-serif",
        fontSize: 11,
        letterSpacing: '0.22em',
        textTransform: 'uppercase',
        fontWeight: 500,
        transition: 'color 2880ms cubic-bezier(0.22,1,0.36,1)',
      }}>We sell you</div>
    </div>
    <h3
      className="orx-tenet__word"
      data-text={`${word}.`}
      style={{
        fontFamily: "'Instrument Serif', serif",
        fontStyle: 'italic',
        fontSize: 'clamp(54px, 5.5vw, 72px)',
        fontWeight: 400,
        letterSpacing: '-0.02em',
        margin: 0,
        lineHeight: 1,
        position: 'relative',
        display: 'inline-block',
        transition: 'text-shadow 2880ms cubic-bezier(0.22,1,0.36,1)',
      }}
    >{word}.</h3>
    <p style={{
      fontFamily: "'Inter Tight', sans-serif",
      fontSize: 15,
      lineHeight: 1.65,
      color: '#BFB3A2',
      margin: 0,
      textWrap: 'pretty',
    }}>{body}</p>
  </div>
));

const Philosophy = () => {
  const tenets = [
    {
      n: '01',
      word: 'Time',
      body:
        'Time is the only non-renewable resource. We buy yours back through deterministic automation, agentic delegation, and streamlined systems. We handle the "how" so you can reclaim the "now."',
    },
    {
      n: '02',
      word: 'Wealth',
      body:
        'Time is leverage, and paired with strategic execution is profit. By implementing sophisticated strategies that expand your margins and compress your costs, we generate abundant value that directly benefits both you and the market you serve.',
    },
    {
      n: '03',
      word: 'Scale',
      body:
        'Wealth is the fuel for exponential growth. Once we have established your operational foundations and built the systems on top, capital can be poured in to generate outsized returns, ensuring your growth flows as fast as your ambition.',
    },
    {
      n: '04',
      word: 'Freedom',
      body:
        'The right to be unencumbered. We believe in the sovereignty of the individual; our mission is to build robust infrastructure so that your presence becomes a choice. This allows you to pursue other ventures or hone in on the vision while your enterprise fulfills on it.',
    },
  ];

  const cardsRef = React.useRef([]);
  // Default accent is Time (index 0). Hover promotes a different tenet and
  // that one STAYS selected after the cursor leaves — same persistent
  // behavior the marquee pills and Engagement paths use.
  const [activeIdx, setActiveIdx] = React.useState(0);
  // Ref, not state: changing it shouldn't re-run the scroll-pick effect.
  const hoverLockedRef = React.useRef(false);

  // Scroll-pick only runs on mobile layouts (single-column stack). Desktop
  // relies on hover persistence alone — we deliberately don't reset
  // activeIdx when the media query flips, so the last-hovered tenet
  // remains lit.
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 900px)');
    let raf = 0;
    const pick = () => {
      if (hoverLockedRef.current) return;
      if (!mq.matches) return;
      const mid = window.innerHeight / 2;
      let best = 0;
      let bestDist = Infinity;
      cardsRef.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const c = r.top + r.height / 2;
        const d = Math.abs(c - mid);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      setActiveIdx(best);
    };
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(pick);
    };
    pick();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    mq.addEventListener?.('change', onScroll);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      mq.removeEventListener?.('change', onScroll);
    };
  }, []);

  return (
    <section style={{
      padding: '128px 48px',
      background: '#0A0705',
      borderBottom: '1px solid rgba(245,238,228,0.06)',
    }}>
      <div style={{maxWidth: 1280, margin: '0 auto'}}>
        <div className="orx-reveal" style={{maxWidth: 820, marginBottom: 72}}>
          <div style={{
            fontFamily: "'Inter Tight', sans-serif",
            fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
            color: '#FFA566', marginBottom: 20,
          }}>Philosophy</div>
          <h2 style={{
            fontFamily: "'Inter Tight', sans-serif",
            fontSize: 'clamp(36px, 5vw, 72px)',
            fontWeight: 400, lineHeight: 1.0, letterSpacing: '-0.04em',
            color: '#FFFAF5', margin: 0, textWrap: 'pretty',
          }}>
            Four things we sell.<br/>{' '}
            <span style={{fontFamily: "'Instrument Serif', serif", fontStyle: 'italic'}}>In that order.</span>
          </h2>
          <p style={{
            fontFamily: "'Inter Tight', sans-serif",
            fontSize: 17, lineHeight: 1.6, color: '#BFB3A2',
            margin: '28px 0 0', maxWidth: 940,
          }}>
            One compounds into the next. Time becomes wealth. Wealth becomes scale. Scale becomes freedom.
          </p>
        </div>

        <div
          className="orx-tenet-grid orx-reveal"
          onMouseEnter={() => { hoverLockedRef.current = true; }}
          onMouseLeave={() => { hoverLockedRef.current = false; }}
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, 1fr)',
            gap: 20,
          }}
        >
          {/* Reveal applied to the whole grid so all four tenets blur in as
              one gesture — Time/Wealth and Scale/Freedom no longer trigger
              on separate scroll thresholds. The wrap itself carries the
              dynamic is-active class; React re-rendering the inner
              className doesn't touch the outer grid's is-revealed. */}
          {tenets.map((t, i) => (
            <div
              key={t.n}
              className={'orx-tenet-wrap' + (activeIdx === i ? ' is-active' : '')}
              // Only a real mouse pointer promotes a tenet on enter. Taps
              // on a touch screen should NOT activate (the scroll-pick in
              // useEffect already drives activeIdx on mobile, and the
              // scroll-triggered ring is the only animation meant for
              // touch). Pen pointers get the mouse behavior.
              onPointerEnter={(e) => {
                if (e.pointerType === 'touch') return;
                setActiveIdx(i);
              }}
            >
              <Tenet
                ref={(el) => (cardsRef.current[i] = el)}
                {...t}
              />
            </div>
          ))}
        </div>
      </div>

      <style>{`
        /* Dim / default state (shared). */
        .orx-tenet {
          background: #120D08;
          border: 1px solid rgba(245,238,228,0.08);
          box-shadow: 0 6px 24px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.03);
        }
        .orx-tenet .orx-tenet__num  { color: #8A7F70; }
        .orx-tenet .orx-tenet__verb { color: #5C5246; }
        .orx-tenet .orx-tenet__word {
          color: #FFFAF5;
          text-shadow: none;
        }
        /* Gradient overlay — same ::before trick used for Results. The base
           text stays solid white; the gradient-filled overlay fades in on
           accent and back out smoothly, never passing through transparent. */
        .orx-tenet__word::before {
          content: attr(data-text);
          position: absolute;
          left: 0; top: 0;
          background: linear-gradient(180deg, #FFE3CC 0%, #FF8533 100%);
          -webkit-background-clip: text;
                  background-clip: text;
          color: transparent;
          opacity: 0;
          transition: opacity 1200ms cubic-bezier(0.22,1,0.36,1);
          pointer-events: none;
          font-family: inherit;
          font-style: inherit;
          font-weight: inherit;
          letter-spacing: inherit;
        }

        /* Accent state. Only one card lights at a time. */
        .orx-tenet-grid:hover .orx-tenet-wrap:hover .orx-tenet,
        .orx-tenet-wrap.is-active .orx-tenet {
          background: linear-gradient(180deg, #1C140D 0%, #120D08 100%);
          border-color: rgba(255,106,10,0.28);
          box-shadow:
            0 0 0 1px rgba(255,106,10,0.28),
            0 24px 60px rgba(255,106,10,0.12),
            inset 0 1px 0 rgba(255,255,255,0.04);
          transform: translateY(-2px);
        }
        .orx-tenet-grid:hover .orx-tenet-wrap:hover .orx-tenet .orx-tenet__num,
        .orx-tenet-wrap.is-active .orx-tenet .orx-tenet__num  { color: #FFA566; }
        .orx-tenet-grid:hover .orx-tenet-wrap:hover .orx-tenet .orx-tenet__verb,
        .orx-tenet-wrap.is-active .orx-tenet .orx-tenet__verb { color: #FFA566; }
        .orx-tenet-grid:hover .orx-tenet-wrap:hover .orx-tenet .orx-tenet__word,
        .orx-tenet-wrap.is-active .orx-tenet .orx-tenet__word {
          text-shadow: 0 0 42px rgba(255, 133, 51, 0.22);
        }
        .orx-tenet-grid:hover .orx-tenet-wrap:hover .orx-tenet .orx-tenet__word::before,
        .orx-tenet-wrap.is-active .orx-tenet .orx-tenet__word::before {
          opacity: 1;
        }

        @media (max-width: 900px) {
          .orx-tenet-grid { grid-template-columns: 1fr !important; }
        }
        /* Mobile compactness — the desktop tenet card is far too tall and
           the italic word is huge relative to a phone viewport. Shrink
           everything so four tenets feel like a concise manifesto strip,
           not four full-screen hero blocks. */
        @media (max-width: 720px) {
          .orx-tenet {
            min-height: 0 !important;
            padding: 28px 24px !important;
            gap: 14px !important;
          }
          .orx-tenet__word {
            font-size: clamp(40px, 12vw, 52px) !important;
          }
          .orx-tenet p {
            font-size: 14px !important;
            line-height: 1.55 !important;
          }
        }
      `}</style>
    </section>
  );
};

window.Philosophy = Philosophy;
window.Tenet = Tenet;
