/* Triventa: shared site chrome (header, footer, heros, CTA, FAQ, legal renderer).
   Loaded as <script type="text/babel" src="site-common.jsx"> before each page script. */
const DS = window.TriventaDesignSystem_31e114;
const { Logo, Button, Icon, Badge } = DS;
const A = 'assets';
const APP_URL = window.PUBLIC_APP_URL || 'https://www.app.triventa.cl/';
const WA_PHONE = '56938961140';
const wa = (text) => 'https://wa.me/' + WA_PHONE + '?text=' + encodeURIComponent(text);
const WA_VENDEDOR = wa('Hola, quiero vender con Triventa. Me gustaría solicitar acceso como vendedor.');
const WA_EMPRESA = wa('Hola, quiero sumar mi empresa a Triventa y agendar una demostración.');

const NAV = [
  ['Para vendedores', 'vendedores.html'],
  ['Para empresas', 'empresas.html'],
  ['Cómo funciona', 'como-funciona.html'],
  ['Tecnología', 'tecnologia.html'],
  ['Misiones', 'misiones.html'],
  ['Nosotros', 'nosotros.html'],
];

function SiteHeader({ active }) {
  const [open, setOpen] = React.useState(false);
  React.useEffect(()=>{
    if(!open) return;
    const close=(e)=>{ if(!e.target.closest('.site-h')) setOpen(false); };
    document.addEventListener('click',close);
    return ()=>document.removeEventListener('click',close);
  },[open]);
  return (
    <header className="site-h" style={{position:'sticky',top:0,zIndex:40,background:'rgba(255,255,255,.92)',backdropFilter:'blur(10px)',borderBottom:'1px solid var(--border-subtle)'}}>
      <style>{'@media(max-width:1020px){.site-h{position:static!important}}'}</style>
      <div className="wrap" style={{display:'flex',alignItems:'center',gap:20,height:72}}>
        <a href="index.html" style={{display:'flex',flexShrink:0}} aria-label="Triventa, inicio"><Logo variant="full" base={A} height={30}/></a>
        <nav className="nav-desktop" aria-label="Principal" style={{display:'flex',gap:20,marginLeft:6}}>
          {NAV.map(([n,href])=>(
            <a key={href} href={href} style={{fontSize:14,fontWeight:active===href?700:500,color:active===href?'var(--triventa-navy)':'var(--text-secondary)',textDecoration:'none',whiteSpace:'nowrap',padding:'6px 0',borderBottom:active===href?'2px solid var(--corp-blue)':'2px solid transparent'}}>{n}</a>
          ))}
        </nav>
        <div style={{marginLeft:'auto',display:'flex',gap:10,alignItems:'center'}}>
          <a href={APP_URL} style={{textDecoration:'none'}} className="nav-desktop"><Button variant="ghost" size="sm" icon="log-in">Ingresar</Button></a>
          <a href="contacto.html#empresas" style={{textDecoration:'none'}}><Button variant="primary" size="sm">Solicitar demostración</Button></a>
          <button className="nav-burger" aria-label="Menú" aria-expanded={open} onClick={()=>setOpen(!open)} style={{display:'none',border:'none',background:'transparent',cursor:'pointer',color:'var(--triventa-navy)',padding:8}}>
            <Icon name={open?'x':'menu'} size={24}/>
          </button>
        </div>
      </div>
      {open && (
        <nav aria-label="Móvil" style={{borderTop:'1px solid var(--border-subtle)',background:'#fff',padding:'10px 24px 18px',display:'flex',flexDirection:'column'}}>
          {NAV.map(([n,href])=>(
            <a key={href} href={href} onClick={()=>setOpen(false)} style={{padding:'13px 4px',minHeight:44,display:'flex',alignItems:'center',fontSize:16,fontWeight:600,color:'var(--triventa-navy)',textDecoration:'none',borderBottom:'1px solid var(--slate-100)'}}>{n}</a>
          ))}
          <a href={APP_URL} style={{padding:'13px 4px',minHeight:44,display:'flex',alignItems:'center',gap:8,fontSize:16,fontWeight:600,color:'var(--corp-blue)',textDecoration:'none'}}><Icon name="log-in" size={18}/><span>Ingresar</span></a>
        </nav>
      )}
    </header>
  );
}

function Breadcrumbs({ trail }) {
  return (
    <nav aria-label="Breadcrumb" style={{fontSize:12.5,color:'var(--text-muted)',display:'flex',gap:8,alignItems:'center',flexWrap:'wrap'}}>
      <a href="index.html" style={{color:'var(--text-muted)',textDecoration:'none'}}>Inicio</a>
      {trail.map((t,i)=>(<React.Fragment key={i}><Icon name="chevron-right" size={12}/><span style={{color:i===trail.length-1?'var(--text-secondary)':'var(--text-muted)',fontWeight:i===trail.length-1?600:400}}>{t}</span></React.Fragment>))}
    </nav>
  );
}

function PageHero({ eyebrow, title, lead, trail, children, tone='light' }) {
  const dark = tone==='navy';
  return (
    <section style={{background:dark?'var(--triventa-navy)':'var(--slate-50)',padding:'40px 0 64px',borderBottom:dark?'none':'1px solid var(--border-subtle)'}}>
      <div className="wrap">
        <div style={{maxWidth:760}}>
          {eyebrow && <span className="eyebrow" style={dark?{color:'var(--vivid-teal)'}:{}}>{eyebrow}</span>}
          <h1 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:46,lineHeight:1.08,letterSpacing:'-0.02em',color:dark?'#fff':'var(--text-heading)',margin:'14px 0 0'}}>{title}</h1>
          {lead && <p style={{fontSize:18.5,lineHeight:1.6,color:dark?'var(--text-on-dark-muted)':'var(--text-secondary)',margin:'18px 0 0',maxWidth:640}}>{lead}</p>}
          {children}
        </div>
      </div>
    </section>
  );
}

function SectionHead({ eyebrow, title, lead, center=true, maxWidth=680 }) {
  return (
    <div style={{maxWidth,margin:center?'0 auto 44px':'0 0 40px',textAlign:center?'center':'left'}}>
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      <h2 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:34,lineHeight:1.15,letterSpacing:'-0.015em',color:'var(--text-heading)',margin:'12px 0 0'}}>{title}</h2>
      {lead && <p style={{fontSize:16.5,lineHeight:1.6,color:'var(--text-secondary)',margin:'14px 0 0'}}>{lead}</p>}
    </div>
  );
}

function Check({ children, tone='var(--corp-blue)' }) {
  return (
    <li style={{display:'flex',alignItems:'flex-start',gap:10,fontSize:15,lineHeight:1.55,color:'var(--text-primary)'}}>
      <Icon name="check" size={17} strokeWidth={2.4} color={tone} style={{flexShrink:0,marginTop:3}}/>
      <span>{children}</span>
    </li>
  );
}

function FAQ({ items }) {
  const [openIdx, setOpenIdx] = React.useState(0);
  return (
    <div style={{display:'flex',flexDirection:'column',gap:10,maxWidth:760,margin:'0 auto'}}>
      {items.map((it,i)=>{
        const open = openIdx===i;
        return (
          <div key={i} style={{background:'#fff',border:'1px solid var(--border-subtle)',borderRadius:12,overflow:'hidden'}}>
            <button onClick={()=>setOpenIdx(open?-1:i)} aria-expanded={open} style={{width:'100%',display:'flex',alignItems:'center',justifyContent:'space-between',gap:16,padding:'16px 20px',minHeight:44,border:'none',background:'transparent',cursor:'pointer',textAlign:'left',fontFamily:'var(--font-display)',fontWeight:600,fontSize:15.5,color:'var(--text-heading)'}}>
              {it.q}<Icon name="chevron-down" size={18} color="var(--text-muted)" style={{flexShrink:0,transform:open?'rotate(180deg)':'none',transition:'transform .18s ease'}}/>
            </button>
            {open && <div style={{padding:'0 20px 18px',fontSize:14.5,lineHeight:1.65,color:'var(--text-secondary)'}}>{it.a}</div>}
          </div>
        );
      })}
    </div>
  );
}

function CTASection() {
  return (
    <section style={{background:'var(--slate-50)'}}>
      <div className="wrap">
        <div style={{background:'var(--triventa-navy)',borderRadius:'var(--radius-2xl)',padding:'52px 48px',display:'flex',alignItems:'center',justifyContent:'space-between',gap:32,flexWrap:'wrap',boxShadow:'var(--shadow-navy)'}}>
          <div style={{maxWidth:560}}>
            <h2 style={{fontFamily:'var(--font-display)',color:'#fff',fontWeight:700,fontSize:32,letterSpacing:'-0.015em',margin:0}}>Encuentra tu lugar en la red Triventa.</h2>
            <p style={{color:'var(--text-on-dark-muted)',fontSize:16.5,margin:'12px 0 0',lineHeight:1.6}}>Vende a tu ritmo o amplía la cobertura comercial de tu empresa. El acceso de vendedores se realiza por invitación y las empresas pueden solicitar una demostración.</p>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:12}}>
            <a href="contacto.html#vendedores" style={{textDecoration:'none'}}><Button variant="territory" size="lg" block>Solicitar acceso</Button></a>
            <a href="contacto.html#empresas" style={{textDecoration:'none'}}><Button variant="accent" size="lg" block>Solicitar demostración</Button></a>
          </div>
        </div>
      </div>
    </section>
  );
}

function SiteFooter() {
  const cols = [
    ['Producto', [['Para vendedores','vendedores.html'],['Para empresas','empresas.html'],['Cómo funciona','como-funciona.html'],['Tecnología','tecnologia.html']]],
    ['Recursos', [['Misiones','misiones.html'],['Cartera protegida','cartera-protegida.html'],['Nosotros','nosotros.html'],['Contacto','contacto.html']]],
    ['Legal', [['Política de privacidad','privacidad.html'],['Términos y condiciones','terminos.html']]],
  ];
  return (
    <footer style={{background:'var(--vivid-navy)',color:'var(--text-on-dark-muted)',padding:'56px 0 36px'}}>
      <div className="wrap" style={{display:'grid',gridTemplateColumns:'1.4fr 1fr 1fr 1.2fr',gap:32}}>
        <div>
          <span style={{background:'#fff',borderRadius:10,padding:'10px 14px',display:'inline-flex'}}><Logo variant="full" base={A} height={26}/></span>
          <p style={{fontSize:13.5,lineHeight:1.6,marginTop:16,maxWidth:280}}>Triventa conecta vendedores independientes, empresas y clientes reales mediante una operación comercial guiada por tecnología.</p>
        </div>
        {cols.map(([t,items])=>(
          <div key={t}>
            <div style={{color:'#fff',fontWeight:700,fontSize:13,marginBottom:14}}>{t}</div>
            {items.map(([n,href])=><a key={href} href={href} style={{display:'block',fontSize:13.5,color:'var(--text-on-dark-muted)',textDecoration:'none',marginBottom:9}}>{n}</a>)}
          </div>
        ))}
      </div>
      <div className="wrap" style={{borderTop:'1px solid rgba(255,255,255,.1)',marginTop:36,paddingTop:20,fontSize:12.5,display:'flex',justifyContent:'space-between',flexWrap:'wrap',gap:12}}>
        <span>© 2026 Triventa. Todos los derechos reservados.</span>
        <span style={{letterSpacing:'.22em'}}>CONECTA · IMPULSA · CRECE</span>
      </div>
    </footer>
  );
}

/* Minimal markdown renderer for the legal documents (headings, bold, lists, hr, front-matter notice). */
function mdToNodes(md) {
  let body = md;
  let notice = null;
  if (body.startsWith('---')) {
    const end = body.indexOf('---', 3);
    if (end > 0) { notice = body.slice(3, end).replace(/aviso_preliminar:\s*/,'').replace(/^"|"$/g,'').trim(); body = body.slice(end+3); }
  }
  const inline = (s) => {
    const parts = [];
    let rest = s, k = 0;
    while (rest.length) {
      const m = rest.match(/\*\*([^*]+)\*\*|\*([^*]+)\*/);
      if (!m) { parts.push(rest); break; }
      if (m.index > 0) parts.push(rest.slice(0, m.index));
      parts.push(<b key={k++}>{m[1] || m[2]}</b>);
      rest = rest.slice(m.index + m[0].length);
    }
    return parts;
  };
  const lines = body.split('\n');
  const out = [];
  let list = null, key = 0;
  const flush = () => { if (list) { out.push(<ul key={key++} style={{margin:'10px 0 16px',paddingLeft:22,display:'flex',flexDirection:'column',gap:6}}>{list}</ul>); list = null; } };
  for (const raw of lines) {
    const l = raw.trimEnd();
    if (/^\s*[-*] /.test(l)) { (list = list || []).push(<li key={key++} style={{fontSize:14.5,lineHeight:1.65,color:'var(--text-secondary)'}}>{inline(l.replace(/^\s*[-*] /,''))}</li>); continue; }
    flush();
    if (!l.trim()) continue;
    if (l === '---') { out.push(<hr key={key++} style={{border:'none',borderTop:'1px solid var(--border-subtle)',margin:'28px 0'}}/>); continue; }
    if (l.startsWith('### ')) out.push(<h3 key={key++} style={{fontFamily:'var(--font-display)',fontWeight:600,fontSize:17,color:'var(--text-heading)',margin:'24px 0 8px'}}>{inline(l.slice(4))}</h3>);
    else if (l.startsWith('## ')) out.push(<h2 key={key++} style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:22,letterSpacing:'-0.01em',color:'var(--text-heading)',margin:'36px 0 10px'}}>{inline(l.slice(3))}</h2>);
    else if (l.startsWith('# ')) continue; /* page renders its own H1 */
    else out.push(<p key={key++} style={{fontSize:14.5,lineHeight:1.7,color:'var(--text-secondary)',margin:'0 0 14px'}}>{inline(l)}</p>);
  }
  flush();
  return { notice, out };
}

function LegalPage({ active, title, src, trail }) {
  const [md, setMd] = React.useState(null);
  const [err, setErr] = React.useState(false);
  React.useEffect(()=>{ fetch(src).then(r=>r.text()).then(setMd).catch(()=>setErr(true)); },[src]);
  const parsed = md ? mdToNodes(md) : null;
  return (
    <div>
      <SiteHeader active={active}/>
      <PageHero title={title} trail={trail}/>
      <main>
        <section style={{padding:'56px 0 84px'}}>
          <div className="wrap" style={{maxWidth:860}}>
            {err && <p style={{color:'var(--status-danger)'}}>No fue posible cargar el documento. Verifica que el archivo exista en <code>legal/</code>.</p>}
            {!md && !err && <p style={{color:'var(--text-muted)'}}>Cargando documento…</p>}
            {parsed && parsed.out}
          </div>
        </section>
      </main>
      <SiteFooter/>
    </div>
  );
}

Object.assign(window, { DS, A, APP_URL, NAV, wa, WA_VENDEDOR, WA_EMPRESA, SiteHeader, SiteFooter, Breadcrumbs, PageHero, SectionHead, Check, FAQ, CTASection, LegalPage, mdToNodes });
