// page-spine.jsx — "The Through-Line" landing page (standalone, fully responsive).
// One continuous orange line threads the page; every section is a node on it.
// Section backgrounds stay neutral so the line is never interrupted. Layout is
// fluid: full-bleed bands + a centred max-width column, so the spine stays
// continuous from nav to footer at any viewport. Theme-aware, defaults dark.

const SPINE_IMG = {
  hero:     'assets/thruline-00-hero.png',     // 928×1152  portrait
  pi:       'assets/thruline-01-pi.png',       // 1024×1024 square
  ep:       'assets/thruline-02-ep.png',       // 1024×1024 square
  training: 'assets/thruline-03-training.png', // 1024×1024 square
  approach: 'assets/thruline-04-approach.png', // 1376×768  wide
};
const SERVICE_SHOTS = [
  { src: SPINE_IMG.pi,       cap: 'Field surveillance' },
  { src: SPINE_IMG.ep,       cap: 'Motorcade · advance detail' },
  { src: SPINE_IMG.training, cap: 'Scenario brief' },
];

function LandingSpine() {
  const [mode, setMode] = React.useState('dark');
  const c = mkTheme(mode);
  const vw = useVW();
  const m = vw < 760;                                   // phone
  const tablet = vw >= 760 && vw < 1080;                // narrow desktop / tablet

  const MAXW = 1280;
  const PADX = m ? 20 : 64;                             // outer horizontal inset
  const SPINE = m ? 24 : (tablet ? 104 : 196);          // spine x within the column
  const GAP = m ? 40 : 92;                              // spine → content gutter
  const CONTENT = SPINE + GAP;

  const black = (s) => ({ fontFamily: '"Archivo", sans-serif', fontWeight: 900, fontSize: s, letterSpacing: '-0.035em', lineHeight: 0.96, margin: 0 });
  const mono = { fontFamily: '"Spline Sans Mono", monospace', fontSize: 12, letterSpacing: '0.24em', textTransform: 'uppercase' };

  // Full-bleed band with a centred max-width column.
  function Band({ bg, children, style }) {
    return (
      <div style={{ background: bg, width: '100%', ...style }}>
        <div style={{ maxWidth: MAXW, margin: '0 auto', position: 'relative' }}>{children}</div>
      </div>
    );
  }

  // A node-on-the-spine row.
  function Row({ bg, padV = 90, children, node = true, sym }) {
    const pv = m ? Math.round(padV * 0.62) : padV;
    return (
      <Band bg={bg}>
        <div style={{ position: 'relative', padding: `${pv}px ${PADX}px ${pv}px 0` }}>
          <div style={{ position: 'absolute', left: SPINE, top: 0, bottom: 0, width: 3, background: c.orange, zIndex: 0 }} />
          {node && (
            <React.Fragment>
              <div style={{ position: 'absolute', left: SPINE + 3, top: '50%', width: m ? 18 : 46, height: 2, background: c.orange, transform: 'translateY(-1px)', zIndex: 1 }} />
              <div style={{ position: 'absolute', left: SPINE - 14, top: '50%', transform: 'translateY(-50%)', width: 31, height: 31, borderRadius: '50%', background: c.orange, border: `4px solid ${bg}`, boxShadow: `0 0 0 3px ${c.orange}`, zIndex: 2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: '"Archivo", sans-serif', fontWeight: 900, fontSize: 13, color: '#1A1A1A' }}>{sym}</div>
            </React.Fragment>
          )}
          <div style={{ marginLeft: CONTENT, position: 'relative', zIndex: 1 }}>{children}</div>
        </div>
      </Band>
    );
  }

  // Framed photo "plate" — orange rule, image, dossier caption.
  const Shot = ({ fig, src, cap, ratio = '1 / 1', style }) => (
    <figure style={{ margin: 0, minWidth: 0, ...style }}>
      <div style={{ height: 3, background: c.orange }} />
      <div style={{ position: 'relative', width: '100%', aspectRatio: ratio, overflow: 'hidden', background: c.bg3 }}>
        <img src={src} alt={cap} loading="lazy"
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>
    </figure>
  );

  const Field = ({ label, ph, wide, area, select, name, type = 'text', required }) => (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7, gridColumn: wide ? '1 / -1' : 'auto', minWidth: 0 }}>
      <span style={{ ...mono, fontSize: 10.5, color: c.mute }}>{label}{required && <span style={{ color: c.orange }}> *</span>}</span>
      {select ? (
        <select name={name} required={required} style={{ font: '15px "Archivo", sans-serif', color: c.fg, padding: '13px 14px', border: `1px solid ${c.fieldLine}`, borderRadius: 0, background: c.fieldBg, width: '100%' }}>
          {SERVICE_OPTIONS.map((o) => <option key={o}>{o}</option>)}
        </select>
      ) : area ? (
        <textarea name={name} required={required} rows="3" placeholder={ph} style={{ font: '15px "Archivo", sans-serif', color: c.fg, padding: '13px 14px', border: `1px solid ${c.fieldLine}`, borderRadius: 0, background: c.fieldBg, resize: 'vertical', width: '100%' }} />
      ) : (
        <input name={name} type={type} required={required} placeholder={ph} style={{ font: '15px "Archivo", sans-serif', color: c.fg, padding: '13px 14px', border: `1px solid ${c.fieldLine}`, borderRadius: 0, background: c.fieldBg, width: '100%' }} />
      )}
    </label>
  );

  const [submitState, setSubmitState] = React.useState({ status: 'idle', message: '' });
  const handleSubmit = async (e) => {
    e.preventDefault();
    const form = e.currentTarget;
    const fd = new FormData(form);
    const payload = {
      name: fd.get('name') || '',
      organization: fd.get('organization') || '',
      email: fd.get('email') || '',
      service: fd.get('service') || '',
      message: fd.get('message') || '',
    };
    setSubmitState({ status: 'sending', message: '' });
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) {
        setSubmitState({ status: 'success', message: "Thanks — we'll be in touch shortly." });
        form.reset();
      } else {
        setSubmitState({ status: 'error', message: data.error || 'Could not send. Please email us directly.' });
      }
    } catch {
      setSubmitState({ status: 'error', message: 'Network error. Please try again or email us directly.' });
    }
  };

  return (
    <div style={{ width: '100%', background: c.bg, fontFamily: '"Archivo", sans-serif', color: c.fg, overflowX: 'hidden' }}>
      {/* nav */}
      <Band bg={c.bg2} style={{ borderBottom: `1px solid ${c.line}`, position: 'sticky', top: 0, zIndex: 50 }}>
        <nav style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: `${m ? 12 : 18}px ${PADX}px` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <LogoImg h={m ? 30 : 36} />
            <Wordmark size={m ? 16 : 19} color={c.fg} sub={c.mute} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: m ? 10 : 22 }}>
            {!m && !tablet && ['Services', 'Approach', 'Contact'].map((l) => <a key={l} href="#" style={{ ...mono, fontSize: 12, color: c.fg, opacity: 0.75, textDecoration: 'none' }}>{l}</a>)}
            <ThemeToggle mode={mode} setMode={setMode} c={c} />
            {!m && <a href="#contact" style={{ ...mono, fontSize: 12, color: '#1A1A1A', background: c.orange, padding: '11px 16px', textDecoration: 'none', fontWeight: 600 }}>Consultation</a>}
          </div>
        </nav>
      </Band>

      {/* spine start cap */}
      <Band bg={c.bg} style={{ height: 0, overflow: 'visible' }}>
        <div style={{ position: 'absolute', left: SPINE - 9, top: 14, width: 21, height: 21, borderRadius: '50%', background: c.orange, border: `4px solid ${c.bg}`, boxShadow: `0 0 0 3px ${c.orange}`, zIndex: 51 }} />
      </Band>

      {/* hero */}
      <Row bg={c.bg} padV={m ? 70 : 96} node={false}>
        <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : '1.08fr 0.92fr', gap: m ? 34 : 56, alignItems: 'center' }}>
          <div style={{ minWidth: 0 }}>
            <h1 style={{ ...black(92), fontSize: 'clamp(40px, 8.4vw, 92px)', color: c.fg, margin: 0 }}>Committed<br />to your<br /><span style={{ color: c.orange }}>mission.</span></h1>
            <p style={{ fontSize: m ? 17 : 19, lineHeight: 1.6, color: c.mute, maxWidth: 520, marginTop: 26 }}>{COPY.position}</p>
            <div style={{ display: 'flex', gap: 14, marginTop: 32, flexWrap: 'wrap' }}>
              <a href="#contact" style={{ background: c.orange, color: '#1A1A1A', fontWeight: 800, fontSize: 16, padding: '15px 26px', textDecoration: 'none' }}>Request a Consultation</a>
              <a href="#services" style={{ color: c.fg, fontWeight: 700, fontSize: 16, padding: '15px 22px', textDecoration: 'none', border: `1px solid ${c.line}` }}>Follow the line ↓</a>
            </div>
          </div>
          <Shot fig="FIG.00" src={SPINE_IMG.hero} cap="On post · principal detail" ratio="928 / 1152" />
        </div>
      </Row>

      {/* services intro */}
      <Row bg={c.bg2} sym="◦" padV={40}>
        <div id="services" style={{ ...mono, color: c.orange2 }}>What we do</div>
        <h2 style={{ ...black(40), fontSize: 'clamp(28px, 5vw, 40px)', marginTop: 12, color: c.fg }}>Three service, one through-line.</h2>
      </Row>

      {/* services as nodes */}
      {SERVICES.map((s, i) => (
        <Row key={s.n} bg={i % 2 ? c.bg : c.bg2} sym={s.n} padV={58}>
          <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : '1fr 0.62fr', gap: m ? 26 : 52, alignItems: 'center' }}>
            <div style={{ position: 'relative', minWidth: 0 }}>
              <span style={{ position: 'absolute', right: 0, top: m ? -20 : -40, fontFamily: '"Archivo", sans-serif', fontWeight: 900, fontSize: m ? 64 : 124, lineHeight: 0.7, color: c.amber, letterSpacing: '-0.05em', zIndex: 0, opacity: c.d ? 0.16 : 0.55, pointerEvents: 'none' }}>{s.n}</span>
              <h3 style={{ ...black(46), fontSize: 'clamp(30px, 5.6vw, 46px)', color: c.fg, position: 'relative', zIndex: 1 }}>{s.title}</h3>
              <p style={{ fontSize: m ? 16.5 : 18, lineHeight: 1.6, color: c.mute, maxWidth: 540, marginTop: 14, position: 'relative', zIndex: 1 }}>{s.blurb}</p>
            </div>
            <Shot fig={`FIG.0${i + 1}`} src={SERVICE_SHOTS[i].src} cap={SERVICE_SHOTS[i].cap} ratio="1 / 1" />
          </div>
        </Row>
      ))}

      {/* approach */}
      <Row bg={c.bg} sym="✦" padV={84}>
        <div id="approach" style={{ ...mono, color: c.orange2 }}>Our approach</div>
        <h2 style={{ ...black(56), fontSize: 'clamp(32px, 6.4vw, 56px)', color: c.fg, marginTop: 14 }}>We start with<br />your <span style={{ color: c.orange }}>mission.</span></h2>
        <p style={{ fontSize: m ? 18 : 21, lineHeight: 1.55, color: c.fg, fontWeight: 500, maxWidth: 700, marginTop: 22 }}>{COPY.approach}</p>
        <div style={{ display: 'flex', gap: m ? 16 : 26, marginTop: 30, flexWrap: 'wrap' }}>
          {['Commitment', 'Professionalism', 'Safety', 'Partnership'].map((p) => (
            <span key={p} style={{ ...mono, fontSize: 12.5, color: c.fg, borderBottom: `2px solid ${c.orange}`, paddingBottom: 4 }}>{p}</span>
          ))}
        </div>
        <Shot fig="FIG.04" src={SPINE_IMG.approach} cap="Operations room" ratio="1376 / 768" style={{ marginTop: 42, maxWidth: 820 }} />
      </Row>

      {/* contact node */}
      <Row bg={c.bg2} sym="→" padV={84}>
        <div id="contact" style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : '0.8fr 1.2fr', gap: m ? 30 : 56 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ ...mono, color: c.orange }}>Contact</div>
            <h2 style={{ ...black(44), fontSize: 'clamp(30px, 5.4vw, 44px)', color: c.fg, marginTop: 14 }}>The line ends at your mission.</h2>
            <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 16 }}>
              {[['Email', 'contact@thrulinesolutions.com']].map(([k, v]) => (
                <div key={k}><div style={{ ...mono, fontSize: 10.5, color: c.mute }}>{k}</div><div style={{ fontSize: 16, color: c.fg, marginTop: 4, wordBreak: 'break-word' }}>{v}</div></div>
              ))}
            </div>
          </div>
          <form style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : '1fr 1fr', gap: 18, minWidth: 0 }} onSubmit={handleSubmit}>
            <Field label="Name" name="name" ph="Jane Doe" required />
            <Field label="Organization" name="organization" ph="Organization" />
            <Field label="Email" name="email" type="email" ph="jane@org.com" required />
            <Field label="Service interest" name="service" select wide />
            <Field label="Message" name="message" ph="How can we support your mission?" area wide required />
            <button
              type="submit"
              disabled={submitState.status === 'sending' || submitState.status === 'success'}
              style={{
                gridColumn: '1 / -1',
                background: submitState.status === 'success' ? c.line : c.orange,
                color: '#1A1A1A',
                border: 'none',
                fontFamily: '"Archivo", sans-serif',
                fontWeight: 800,
                fontSize: 16,
                padding: '17px',
                cursor: submitState.status === 'sending' || submitState.status === 'success' ? 'default' : 'pointer',
                opacity: submitState.status === 'sending' ? 0.7 : 1,
              }}>
              {submitState.status === 'sending' ? 'Sending…'
                : submitState.status === 'success' ? '✓ Sent'
                : 'Request a Consultation →'}
            </button>
            {submitState.message && (
              <div role="status" style={{
                gridColumn: '1 / -1',
                ...mono,
                fontSize: 13,
                padding: '12px 14px',
                background: submitState.status === 'success' ? 'rgba(236,90,20,0.08)' : 'rgba(220,38,38,0.08)',
                borderLeft: `3px solid ${submitState.status === 'success' ? c.orange : '#dc2626'}`,
                color: c.fg,
              }}>{submitState.message}</div>
            )}
          </form>
        </div>
      </Row>

      {/* arrowhead terminator */}
      <Band bg={c.bg} style={{ paddingBottom: 64 }}>
        <div style={{ position: 'relative', height: 56 }}>
          <div style={{ position: 'absolute', left: SPINE, top: 0, height: 30, width: 3, background: c.orange }} />
          <div style={{ position: 'absolute', left: SPINE - 13.5, top: 30, width: 0, height: 0, borderLeft: '15px solid transparent', borderRight: '15px solid transparent', borderTop: `22px solid ${c.orange}` }} />
          <div style={{ position: 'absolute', left: SPINE + 44, top: 22, ...mono, fontSize: 11, color: c.mute }}>Mission</div>
        </div>
      </Band>

      {/* footer */}
      <Band bg={c.bg2} style={{ borderTop: `1px solid ${c.line}` }}>
        <footer style={{ padding: `${m ? 28 : 34}px ${PADX}px ${m ? 36 : 44}px`, display: 'flex', flexDirection: m ? 'column' : 'row', justifyContent: 'space-between', alignItems: m ? 'flex-start' : 'center', gap: m ? 16 : 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <LogoImgFlat h={28} />
            <Wordmark size={17} color={c.fg} sub={c.mute} />
          </div>
          <div style={{ ...mono, fontSize: 11, color: c.mute }}>© 2026 · Committed to your mission</div>
        </footer>
      </Band>
    </div>
  );
}
window.LandingSpine = LandingSpine;
