// ─────────────────────────────────────────────────────────────
// legal.jsx — shared layout for the four ComposerOS legal pages.
// Renders a page from window.LEGAL_PAGES[key]: title block, auto TOC
// from section headings, sections with block renderers, shared footer.
// Reuses the site system (Inter Tight + JetBrains Mono, paper bg, moss
// accent, mono eyebrows) and the dark SiteFooter from website.jsx.
// ─────────────────────────────────────────────────────────────

const L_BG    = '#faf8f5';
const L_INK   = '#1c1a17';
const L_SOFT  = 'rgba(28,26,23,0.66)';
const L_MUTE  = 'rgba(28,26,23,0.46)';
const L_LINE  = 'rgba(28,26,23,0.10)';
const L_MOSS  = '#6d8b7a';
const L_OCHRE = '#b07c44';   // legal accent — warm, slightly deeper than hero ochre
const L_HOME  = '/';

const L_SHELL = { maxWidth:1120, margin:'0 auto', padding:'0 clamp(20px, 4vw, 48px)' };

const L_NAV = [
  { key:'privacy',  label:'Privacy',  href:'/privacy' },
  { key:'terms',    label:'Terms',    href:'/terms' },
  { key:'security', label:'Security', href:'/security' },
  { key:'cookies',  label:'Cookies',  href:'/cookies' },
];

function LEyebrow({ children, color = L_OCHRE, style }) {
  return (
    <div style={{
      fontFamily:"'JetBrains Mono',ui-monospace,monospace",
      fontSize:11, letterSpacing:1.8, textTransform:'uppercase',
      color, fontWeight:600, ...style,
    }}>{children}</div>
  );
}

// ── Header — mirrors the site header; links back to the main site ──
function LegalHeader({ activeKey }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive:true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const tone = (typeof ORBIT_PALETTE !== 'undefined') ? ORBIT_PALETTE.moss : null;
  return (
    <header className="legal-header" style={{
      position:'sticky', top:0, zIndex:50,
      background: scrolled ? 'rgba(250,248,245,0.85)' : 'rgba(250,248,245,0)',
      backdropFilter: scrolled ? 'saturate(180%) blur(14px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'saturate(180%) blur(14px)' : 'none',
      borderBottom: `1px solid ${scrolled ? L_LINE : 'transparent'}`,
      transition:'background 300ms, border-color 300ms, backdrop-filter 300ms',
    }}>
      <div style={{ ...L_SHELL, maxWidth:1200, height:64, display:'flex', alignItems:'center', justifyContent:'space-between', gap:20 }}>
        <a href={L_HOME} style={{display:'flex',alignItems:'center',gap:10,textDecoration:'none',color:L_INK}}>
          <div style={{width:28,height:28,display:'flex',alignItems:'center',justifyContent:'center'}}>
            {tone ? <OrbitIcon size={28} tone={tone}/> : <div style={{width:22,height:22,borderRadius:11,background:`conic-gradient(from 0deg, ${L_INK}, ${L_MOSS}, ${L_INK})`}}/>}
          </div>
          <div style={{fontSize:17,fontWeight:500,letterSpacing:-0.3}}>Composer<span style={{opacity:0.55}}>OS</span></div>
        </a>
        <nav className="legal-nav-desktop" style={{display:'flex',alignItems:'center',gap:30,fontSize:14,color:L_SOFT}}>
          {L_NAV.map(i => (
            <a key={i.key} href={i.href}
               style={{color: i.key===activeKey ? L_INK : 'inherit', fontWeight: i.key===activeKey ? 500 : 400, textDecoration:'none', transition:'color 150ms'}}
               onMouseOver={e=>e.currentTarget.style.color=L_INK}
               onMouseOut={e=>e.currentTarget.style.color = i.key===activeKey ? L_INK : L_SOFT}>{i.label}</a>
          ))}
          <a href={L_HOME} style={{
            padding:'9px 18px',borderRadius:999,fontSize:14,fontWeight:500,whiteSpace:'nowrap',
            background:L_INK,color:L_BG,textDecoration:'none',transition:'background 160ms',
          }}
          onMouseOver={e=>e.currentTarget.style.background='#5f7d63'}
          onMouseOut={e=>e.currentTarget.style.background=L_INK}>Back to site</a>
        </nav>
        <button className="legal-nav-mobile-btn" onClick={()=>setOpen(v=>!v)}
          aria-label="Menu" style={{display:'none',background:'transparent',border:'none',cursor:'pointer',padding:8,color:L_INK}}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            {open
              ? <g stroke="currentColor" strokeWidth="1.8"><line x1="5" y1="5" x2="17" y2="17"/><line x1="17" y1="5" x2="5" y2="17"/></g>
              : <g stroke="currentColor" strokeWidth="1.8"><line x1="3" y1="7" x2="19" y2="7"/><line x1="3" y1="13" x2="19" y2="13"/></g>}
          </svg>
        </button>
      </div>
      {open && (
        <div className="legal-mobile-panel" style={{ background:L_BG, borderTop:`1px solid ${L_LINE}`, padding:'12px 20px 20px', display:'flex', flexDirection:'column', gap:4 }}>
          {L_NAV.map(i=>(
            <a key={i.key} href={i.href} onClick={()=>setOpen(false)}
              style={{padding:'10px 4px',fontSize:16,color: i.key===activeKey ? L_INK : L_SOFT,fontWeight: i.key===activeKey ? 500 : 400,textDecoration:'none',borderBottom:`1px solid ${L_LINE}`}}>{i.label}</a>
          ))}
          <a href={L_HOME} onClick={()=>setOpen(false)} style={{marginTop:14,padding:'12px 0',textAlign:'center',borderRadius:999,background:L_INK,color:L_BG,fontSize:14,fontWeight:500,textDecoration:'none'}}>Back to site</a>
        </div>
      )}
    </header>
  );
}

// ── Block renderers ──────────────────────────────────────────
function LBlock({ block }) {
  const pStyle = { margin:'0 0 18px', fontSize:'clamp(15.5px, 1.05vw, 17.5px)', lineHeight:1.72, color:L_SOFT, letterSpacing:-0.1, textWrap:'pretty' };
  switch (block.t) {
    case 'p':
      return <p style={pStyle} dangerouslySetInnerHTML={{__html: block.html}} />;
    case 'lead':
      return (
        <p style={pStyle}>
          <strong style={{color:L_INK, fontWeight:600}}>{block.term}</strong>{' '}
          <span dangerouslySetInnerHTML={{__html: block.html}} />
        </p>
      );
    case 'h3':
      return <h3 style={{margin:'30px 0 12px', fontSize:'clamp(17px, 1.5vw, 20px)', fontWeight:600, letterSpacing:-0.3, color:L_INK, lineHeight:1.2}}>{block.text}</h3>;
    case 'ul':
      return (
        <ul style={{margin:'0 0 18px', padding:0, listStyle:'none', display:'flex', flexDirection:'column', gap:11}}>
          {block.items.map((it, i) => (
            <li key={i} style={{position:'relative', paddingLeft:26, fontSize:'clamp(15.5px, 1.05vw, 17.5px)', lineHeight:1.62, color:L_SOFT, letterSpacing:-0.1}}>
              <span aria-hidden="true" style={{position:'absolute', left:4, top:'0.62em', width:7, height:7, borderRadius:2, background:L_MOSS, transform:'translateY(-50%) rotate(45deg)'}} />
              <span dangerouslySetInnerHTML={{__html: it}} />
            </li>
          ))}
        </ul>
      );
    case 'quote':
      return (
        <blockquote style={{ margin:'0 0 22px', padding:'4px 0 4px 24px', borderLeft:`3px solid ${L_MOSS}` }}>
          <p style={{margin:0, fontSize:'clamp(18px, 1.7vw, 23px)', lineHeight:1.4, fontStyle:'italic', fontWeight:400, color:L_INK, letterSpacing:-0.4, textWrap:'pretty'}}
             dangerouslySetInnerHTML={{__html: block.html}} />
        </blockquote>
      );
    default:
      return null;
  }
}

// ── Table of contents (auto from sections) ───────────────────
function LegalTOC({ sections, activeId, onJump }) {
  return (
    <nav aria-label="On this page" style={{ position:'sticky', top:96 }}>
      <div style={{ fontFamily:"'JetBrains Mono',ui-monospace,monospace", fontSize:11, letterSpacing:1.8, textTransform:'uppercase', color:L_MUTE, fontWeight:600, marginBottom:16 }}>
        On this page
      </div>
      <ol style={{ listStyle:'none', margin:0, padding:0, display:'flex', flexDirection:'column', gap:2, counterReset:'toc' }}>
        {sections.map(s => {
          const active = s.id === activeId;
          return (
            <li key={s.id}>
              <a href={`#${s.id}`} onClick={(e)=>onJump(e, s.id)}
                style={{
                  display:'block', padding:'7px 0 7px 14px', fontSize:13.5, lineHeight:1.35, textDecoration:'none',
                  color: active ? L_INK : L_MUTE, fontWeight: active ? 500 : 400,
                  borderLeft:`2px solid ${active ? L_MOSS : 'transparent'}`,
                  marginLeft:-2, transition:'color 150ms, border-color 150ms',
                }}
                onMouseOver={e=>{ if(!active) e.currentTarget.style.color=L_SOFT; }}
                onMouseOut={e=>{ if(!active) e.currentTarget.style.color=L_MUTE; }}>
                {s.title}
              </a>
            </li>
          );
        })}
      </ol>
      <button onClick={()=>window.print()} className="legal-print-btn" style={{
        marginTop:24, display:'inline-flex', alignItems:'center', gap:9, padding:'10px 16px',
        background:'transparent', border:`1px solid ${L_LINE}`, borderRadius:999, cursor:'pointer',
        fontFamily:"'Inter Tight',system-ui,sans-serif", fontSize:13, color:L_SOFT, transition:'border-color 150ms, color 150ms',
      }}
        onMouseOver={e=>{ e.currentTarget.style.borderColor=L_MOSS; e.currentTarget.style.color=L_INK; }}
        onMouseOut={e=>{ e.currentTarget.style.borderColor=L_LINE; e.currentTarget.style.color=L_SOFT; }}>
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3">
          <path d="M4 6V2.5h8V6"/><rect x="2.5" y="6" width="11" height="5.5" rx="1"/><path d="M4.5 10.5h7V14h-7z"/>
        </svg>
        Print / Save PDF
      </button>
    </nav>
  );
}

// ── The page ─────────────────────────────────────────────────
function LegalPage({ pageKey }) {
  const page = (window.LEGAL_PAGES || {})[pageKey];
  const [activeId, setActiveId] = React.useState(page ? page.sections[0].id : null);
  const refs = React.useRef({});

  React.useEffect(() => {
    if (!page) return;
    const obs = new IntersectionObserver((entries) => {
      const visible = entries.filter(e=>e.isIntersecting).sort((a,b)=>a.boundingClientRect.top-b.boundingClientRect.top);
      if (visible[0]) setActiveId(visible[0].target.id);
    }, { rootMargin:'-88px 0px -65% 0px', threshold:0 });
    page.sections.forEach(s => { const el = refs.current[s.id]; if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, [page]);

  if (!page) {
    return <div style={{padding:80, textAlign:'center', fontFamily:"'Inter Tight',sans-serif"}}>Unknown legal page: {String(pageKey)}</div>;
  }

  const jump = (e, id) => {
    e.preventDefault();
    const el = refs.current[id];
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 84;
      window.scrollTo({ top:y, behavior:'smooth' });
      history.replaceState(null, '', `#${id}`);
    }
  };

  return (
    <div style={{ background:L_BG, color:L_INK, fontFamily:"'Inter Tight',system-ui,-apple-system,BlinkMacSystemFont,sans-serif", minHeight:'100vh', width:'100%', maxWidth:'100%', overflowX:'hidden' }}>
      <LegalHeader activeKey={pageKey} />

      {/* Title block */}
      <section style={{ ...L_SHELL, paddingTop:'clamp(56px, 8vw, 104px)', paddingBottom:'clamp(28px, 4vw, 44px)' }}>
        <div style={{ maxWidth:760 }}>
          <LEyebrow style={{marginBottom:18}}>{page.eyebrow}</LEyebrow>
          <h1 style={{ margin:0, fontWeight:450, letterSpacing:'-0.04em', lineHeight:0.96, fontSize:'clamp(42px, 6.4vw, 84px)', color:L_INK }}>
            {page.title.length > 1
              ? <>{page.title[0]}<span style={{fontStyle:'italic', fontWeight:350, color:L_OCHRE}}>{page.title[1]}</span></>
              : page.title[0]}
          </h1>
          <div style={{ marginTop:'clamp(18px, 2vw, 26px)', display:'flex', alignItems:'center', gap:14, flexWrap:'wrap', fontFamily:"'JetBrains Mono',ui-monospace,monospace", fontSize:12.5, letterSpacing:0.3, color:L_MUTE }}>
            <span>Last updated · {page.updated}</span>
          </div>
          {page.intro && (
            <p style={{ marginTop:'clamp(22px, 2.4vw, 30px)', maxWidth:680, fontSize:'clamp(16px, 1.25vw, 20px)', lineHeight:1.58, color:L_INK, opacity:0.8, fontWeight:400, textWrap:'pretty' }}>
              {page.intro}
            </p>
          )}
        </div>
      </section>

      {/* Body: TOC + sections */}
      <section style={{ ...L_SHELL, paddingBottom:'clamp(60px, 9vw, 120px)' }}>
        <div className="legal-grid" style={{ display:'grid', gridTemplateColumns:'232px minmax(0, 1fr)', gap:'clamp(36px, 5vw, 80px)', alignItems:'start' }}>
          <aside className="legal-toc">
            <LegalTOC sections={page.sections} activeId={activeId} onJump={jump} />
          </aside>
          <div style={{ maxWidth:720, borderTop:`1px solid ${L_LINE}` }}>
            {page.sections.map((s, i) => (
              <section key={s.id} id={s.id} ref={el => refs.current[s.id] = el}
                style={{ paddingTop:'clamp(34px, 4vw, 52px)', paddingBottom:'4px', scrollMarginTop:88 }}>
                <div style={{ display:'flex', alignItems:'baseline', gap:14, marginBottom:18 }}>
                  <span style={{ fontFamily:"'JetBrains Mono',ui-monospace,monospace", fontSize:13, fontWeight:600, color:L_MOSS, letterSpacing:0.5 }}>
                    {String(i+1).padStart(2,'0')}
                  </span>
                  <h2 style={{ margin:0, fontSize:'clamp(23px, 2.6vw, 32px)', fontWeight:500, letterSpacing:-0.7, lineHeight:1.08, color:L_INK }}>
                    {s.title}
                  </h2>
                </div>
                <div style={{ paddingLeft:0 }}>
                  {s.blocks.map((b, bi) => <LBlock key={bi} block={b} />)}
                </div>
              </section>
            ))}

            <div style={{ marginTop:'clamp(40px, 5vw, 64px)', paddingTop:28, borderTop:`1px solid ${L_LINE}`, fontSize:13.5, color:L_MUTE, lineHeight:1.7 }}>
              <div>NEMM Group Ltd · Squamish, British Columbia, Canada</div>
              <div style={{marginTop:4}}>This document is provided for transparency and may be updated as ComposerOS evolves.</div>
            </div>
          </div>
        </div>
      </section>

      {(typeof SiteFooter !== 'undefined') ? <SiteFooter /> : null}
    </div>
  );
}

window.LegalPage = LegalPage;
