// Letter.jsx — "A Letter From One Owner To Another"
//
// The emotional center of the Qubikos story. Not a product section, not a
// testimonial, not a pitch. The rest of the site explains what Qubikos
// does; this one exists to make the reader feel why it had to exist.
//
// Public brand line born here: "Whatever comes up. We handle it."
// (See .github/BRAND.md for the full internal note — including the internal-only
// creative archetype this section was directed against. That reference
// never appears here or anywhere public.)
//
// The letter used to occupy ~150vh of the page and reveal line-by-line as you
// scrolled past it. It now lives behind a button and opens in a dialog, so the
// page keeps the narrative beat without the height. Two consequences of that
// move are baked in below: spacing is in px rather than vh (viewport-relative
// gaps make no sense inside a fixed-height box), and lines render at once
// instead of on an IntersectionObserver — there is no page scroll to observe.
// A future voiceover pass would need its own fixed-timeline variant.

const { useState: _lUseS, useEffect: _lUseE, useRef: _lUseR } = React;

function reducedMotionPreferred() {
  return typeof window !== 'undefined' && window.matchMedia &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}

function LetterLine({
  children, size = 21, weight = 400, color = 'rgba(245,242,237,0.82)',
  align = 'left', maxWidth = '100%', margin = '0 0 22px',
  mono = false, tracked = false,
}) {
  return (
    <p style={{
      margin, maxWidth, textAlign: align,
      fontFamily: mono ? 'var(--font-mono)' : "'Newsreader', Georgia, 'Times New Roman', serif",
      fontWeight: weight, fontSize: size, lineHeight: mono ? 1.6 : 1.75, color,
      letterSpacing: tracked ? '0.14em' : 'normal',
      textTransform: tracked ? 'uppercase' : 'none',
    }}>{children}</p>
  );
}

const PAIN_LINES = [
  'A coach didn’t show up.',
  'A parent didn’t pay.',
  'Someone needed to change classes.',
  'A lead called while nobody was at the front desk.',
  'Attendance was wrong again.',
];

const FIXER_PAIRS = [
  ['The phone rings.', 'We answer.'],
  ['Someone wants to join.', 'We book them.'],
  ['A payment is due.', 'We collect it.'],
  ['A student walks in.', 'We know they’re there.'],
  ['A coach can’t make it.', 'We find coverage.'],
  ['Someone needs to move classes.', 'It’s handled.'],
];

// The letter itself. Pure content — no open/close concerns, no observers.
function LetterBody() {
  return (
    <div style={{ maxWidth: 560, margin: '0 auto', padding: '8px 4px 0' }}>

      <LetterLine mono tracked size={13} weight={600} color="#8cb0ff" align="center" margin="0 0 96px">
        A letter from one owner to another
      </LetterLine>

      <LetterLine size={30} weight={500} color="#f5f2ed">Dear Owner,</LetterLine>
      <div style={{ height: 32 }} />

      <LetterLine>I've run a gym for over 15 years.</LetterLine>
      <LetterLine margin="0 0 72px">
        And somewhere along the way, I stopped doing the work I was actually good at.
      </LetterLine>

      {PAIN_LINES.map((l, i) => (
        <LetterLine key={l} margin={i === PAIN_LINES.length - 1 ? '0 0 56px' : '0 0 20px'}>{l}</LetterLine>
      ))}

      <LetterLine margin="0 0 40px">None of these problems were big.</LetterLine>
      <LetterLine size={27} weight={600} color="#f5f2ed" align="center" margin="0 0 48px">
        There were just hundreds of them.
      </LetterLine>
      <LetterLine size={20} weight={500} color="rgba(245,242,237,0.60)" align="center" margin="0 0 72px">
        Every day.
      </LetterLine>
      <LetterLine margin="0 0 104px">And somehow, they all became my problem.</LetterLine>

      {/* the turn */}
      <LetterLine size={30} weight={600} color="#fff" align="center" margin="0 0 56px">
        That’s why we built Qubikos.
      </LetterLine>
      <LetterLine align="center" margin="0 0 10px">
        Not to give you another piece of software to manage.
      </LetterLine>
      <LetterLine size={23} weight={600} color="#f5f2ed" align="center" margin="0 0 96px">
        To give your business someone who handles things.
      </LetterLine>

      {/* the fixer sequence */}
      {FIXER_PAIRS.map(([problem, resolution]) => (
        <div key={problem} style={{ marginBottom: 48 }}>
          <LetterLine margin="0 0 4px" color="rgba(245,242,237,0.55)">{problem}</LetterLine>
          <LetterLine weight={600} color="#f5f2ed">{resolution}</LetterLine>
        </div>
      ))}

      <div style={{ height: 24 }} />

      {/* closing */}
      <LetterLine margin="0 0 4px">And when you want something done —</LetterLine>
      <LetterLine weight={600} color="#f5f2ed" margin="0 0 64px">just say it.</LetterLine>

      <LetterLine margin="0 0 4px">You built your business.</LetterLine>
      <LetterLine margin="0 0 96px">
        You shouldn’t have to carry every little thing inside it.
      </LetterLine>

      <LetterLine align="center" color="rgba(245,242,237,0.55)" size={17} margin="0 0 6px">
        — From one owner to another.
      </LetterLine>
      <LetterLine align="center" mono tracked size={12} color="rgba(245,242,237,0.55)" margin="0 0 8px">
        Qubikos
      </LetterLine>
    </div>
  );
}

// Dialog shell. Mirrors DemoVideoModal in Sections.jsx (Escape, backdrop click,
// scroll lock, hero-video pause) and adds focus handling, since this one is a
// long read rather than a video the reader watches and dismisses.
function LetterModal({ open, onClose }) {
  const closeRef = _lUseR(null);

  _lUseE(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    // the looping hero background video sits behind everything on this page —
    // pause it while the dialog is open so it can't bleed through the backdrop
    const bgVideos = document.querySelectorAll('.hero-video-panel video');
    bgVideos.forEach((v) => v.pause());
    if (closeRef.current) closeRef.current.focus();
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
      bgVideos.forEach((v) => v.play().catch(() => {}));
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(5,5,5,0.94)', backdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24, animation: 'qb-fadeIn .25s var(--ease-out) both',
      }}>
      <div
        role="dialog"
        aria-modal="true"
        aria-label="A letter from one owner to another"
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative', width: '100%', maxWidth: 640, maxHeight: '85vh',
          overflowY: 'auto', background: '#050505',
          borderRadius: 20, border: '1px solid rgba(255,255,255,0.10)',
          boxShadow: '0 30px 90px rgba(0,0,0,0.55)',
          padding: '56px 32px 40px',
        }}>
        <button
          ref={closeRef}
          onClick={onClose}
          aria-label="Close the letter"
          style={{
            position: 'sticky', top: 0, float: 'right', marginRight: -8, zIndex: 1,
            width: 36, height: 36, borderRadius: 999, border: '1px solid rgba(255,255,255,0.18)',
            background: 'rgba(6,8,15,0.65)', color: '#fff', fontSize: 18, cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>×</button>
        <LetterBody/>
      </div>
    </div>
  );
}

// The page band that replaces the old full-height section. Keeps the letter's
// beat in the scroll — same eyebrow, same ground — at a fraction of the height.
function LetterTrigger() {
  const [open, setOpen] = _lUseS(false);
  const [ref, seen] = window.useOnScreen({ threshold: 0.4 });
  const [reduced] = _lUseS(reducedMotionPreferred);
  const triggerRef = _lUseR(null);
  const show = reduced || seen;

  const close = () => {
    setOpen(false);
    if (triggerRef.current) triggerRef.current.focus();
  };

  return (
    <section ref={ref} style={{
      background: '#050505', padding: '18vh 24px', textAlign: 'center',
      opacity: show ? 1 : 0, transform: show ? 'none' : 'translateY(10px)',
      transition: 'opacity 1s ease, transform 1s ease',
    }}>
      <p style={{
        margin: '0 0 10px', fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600,
        letterSpacing: '0.14em', textTransform: 'uppercase', color: '#8cb0ff',
      }}>
        A letter from one owner to another
      </p>
      <p style={{
        margin: '0 auto 28px', maxWidth: 460,
        fontFamily: "'Newsreader', Georgia, 'Times New Roman', serif",
        fontSize: 21, lineHeight: 1.75, color: 'rgba(245,242,237,0.82)',
      }}>
        I've run a gym for over 15 years. And somewhere along the way, I stopped
        doing the work I was actually good at.
      </p>
      <span ref={triggerRef} tabIndex={-1}>
        <window.QBButton
          size="lg"
          onClick={() => setOpen(true)}
          icon={<window.QBIcon name="arrow" size={16} />}>
          Read the letter
        </window.QBButton>
      </span>
      <LetterModal open={open} onClose={close}/>
    </section>
  );
}

window.QBLetter = LetterTrigger;
