// ============================================================
// GARABATO · Home Page (sitio real)
// Hero + logos + manifiesto + trabajo + cifras + servicios
// + testimonios + diario + contacto. Datos: window.CONTENT.
// ============================================================

const C = window.CONTENT;
const articleAccent = (category) => ({
  Proceso: 'var(--brand-violet)',
  Tipografía: 'var(--brand-magenta)',
  Cultura: 'var(--brand-yellow)',
  Producto: 'var(--brand-orange)',
  Editorial: 'var(--brand-violet)',
  Motion: 'var(--brand-magenta)',
}[category] || 'var(--brand-violet)');

// ──────────────── HERO ────────────────
const MotionControl = () => {
  const [enabled, setEnabled] = React.useState(() => window.GarabatoFX?.isMotionEnabled() ?? false);
  React.useEffect(() => {
    const onChange = e => setEnabled(e.detail.enabled);
    window.addEventListener('garabato-motion-change', onChange);
    return () => window.removeEventListener('garabato-motion-change', onChange);
  }, []);
  return <button type="button" className="hp-motion-control" aria-pressed={enabled}
    onClick={() => window.GarabatoFX?.setMotion(!enabled)}>
    <Icon name={enabled ? 'pause' : 'play'} size={14}/>
    {enabled ? 'Pausar animación' : 'Reproducir animación'}
  </button>;
};

const BrandIntro = ({onDone}) => {
  const [stage, setStage] = React.useState('logo');
  const [gather, setGather] = React.useState(null);
  const openingRoot = React.useRef(null), openingTimeline = React.useRef({epoch:0,visible:false});
  const colorRoot = React.useRef(null), colorTimeline = React.useRef({epoch:0, visible:false});
  React.useEffect(() => {
    if (!window.GarabatoFX?.isMotionEnabled()) { onDone(); return; }
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const regions = [...document.querySelectorAll('#main, .hp-nav, .hp-footer')];
    regions.forEach(el => el.inert = true);
    const startColors = setTimeout(() => setStage('expand'), 1200);
    const finishZoom = setTimeout(() => setStage('colors'), 2200);
    const collect = setTimeout(() => {
      const logo = document.querySelector('.hp-nav__brand img');
      const rect = logo?.getBoundingClientRect();
      setGather({x: rect ? rect.left + rect.height * .45 : 30, y: rect ? rect.top + rect.height / 2 : 30});
    }, 7600);
    const end = setTimeout(onDone, 9460);
    const onMotion = e => { if (!e.detail.enabled) onDone(); };
    window.addEventListener('garabato-motion-change', onMotion);
    return () => {clearTimeout(startColors);clearTimeout(finishZoom);clearTimeout(collect);clearTimeout(end);document.body.style.overflow=previousOverflow;regions.forEach(el=>el.inert=false);window.removeEventListener('garabato-motion-change',onMotion);};
  }, [onDone]);
  return ReactDOM.createPortal(<div className="brand-intro" role="dialog" aria-modal="true" aria-label="Animación de bienvenida de Garabato">
    {stage !== 'colors' && <div className={'brand-intro__logo ' + (stage === 'expand' ? 'brand-intro__logo--expand' : '')}><div ref={openingRoot} className="brand-intro__isotipo">
        {['curl','ring','hook','dash'].map((variant,i) => <GraphicTrace key={variant} variant={variant} canvasBox="47 41 87 97"
          duration={600} delay={i*70} cycle={20000} timeline={openingTimeline} triggerRef={openingRoot}/>)}
      </div></div>}
    {stage !== 'logo' &&
      <div ref={colorRoot} className="hero-color-wipe brand-intro__sequence" aria-hidden="true">
        {[
          {background:'yellow',variant:'ring',delay:800,fade:600},
          {background:'magenta',variant:'dash',delay:2150,fade:1800},
          {background:'violet',variant:'curl',delay:3500,fade:3150},
          {background:'orange',variant:'hook',delay:4850,fade:4500},
        ].map(screen => <div key={screen.background} className={'hero-color-screen hero-color-screen--'+screen.background} style={{'--screen-enter':screen.fade+'ms'}}>
          <GraphicTrace variant={screen.variant} size="xl" duration={700} delay={screen.delay} cycle={20000} timeline={colorTimeline} triggerRef={colorRoot}/>
        </div>)}
        <div className="hero-color-wipe__white"/>
      </div>}
    {gather && <div className="brand-intro__gather" aria-hidden="true">
      {['curl-yellow','ring-magenta','hook-violet','dash-orange'].map((name,i) => <img key={name} src={'assets/brand/originals/'+name+'.svg'}
        className={'brand-intro__collector brand-intro__collector--'+i} alt="" style={{'--logo-x':gather.x+'px','--logo-y':gather.y+'px'}}/>)}
    </div>}
    <button className="brand-intro__skip" type="button" autoFocus onClick={onDone}>Saltar intro <span aria-hidden="true">→</span></button>
  </div>, document.body);
};

const Hero = () => {
  const heroRef=React.useRef(null), artRef=React.useRef(null);
  const traceTimeline=React.useRef({epoch:0,visible:false});
  const [intro, setIntro]=React.useState(true);
  const finishIntro=React.useCallback(()=>setIntro(false),[]);
  return <>
    {intro && <BrandIntro onDone={finishIntro}/>}
  <section ref={heroRef} className="hp-hero" id="hero">
    <div ref={artRef} className="hp-hero__art" aria-hidden="true">
      <div className="hp-hero__piece hp-hero__piece--curl"><GraphicTrace variant="curl" fullCanvas timeline={traceTimeline} triggerRef={heroRef} cycle={Infinity} delay={0}/></div>
      <div className="hp-hero__piece hp-hero__piece--ring"><GraphicTrace variant="ring" fullCanvas timeline={traceTimeline} triggerRef={heroRef} cycle={Infinity} delay={120}/></div>
      <div className="hp-hero__piece hp-hero__piece--hook"><GraphicTrace variant="hook" fullCanvas timeline={traceTimeline} triggerRef={heroRef} cycle={Infinity} delay={240}/></div>
      <div className="hp-hero__piece hp-hero__piece--dash"><GraphicTrace variant="dash" fullCanvas timeline={traceTimeline} triggerRef={heroRef} cycle={Infinity} delay={360}/></div>
    </div>
    <div className="hp-hero__inner">
      <h1 className="hp-hero__title">
        Diseño que<br/>
        <em className="hp-hero__em">no se parece</em><br/>
        a nada más.
      </h1>
      <p className="hp-hero__sub">
        Somos un estudio de diseño independiente en {C.SITE.city}, {C.SITE.country}. Construimos marcas, productos
        y narrativas con un trazo propio, para equipos que ya tienen algo para decir.
      </p>
      <div className="hp-hero__ctas">
        <a href="#contact" className="btn btn--xl btn--primary hp-hero__button">Hablemos <Icon name="arrow-right" size={18}/></a>
        <a href="#work" className="btn btn--xl btn--secondary">Ver el trabajo</a>
      </div>
      <a href="#work" className="hp-hero__scroll">
        <Icon name="arrow-down" size={14}/>
        <span>Conocé el estudio</span>
      </a>
      <MotionControl/>
    </div>
  </section>
  </>;
};

// ──────────────── LOGOS ────────────────
const HeroBullets = () => (
  <section className="hp-hero-bullets" aria-label="Nuestro enfoque">
    <ul className="hp-hero-bullets__list">
      {[
        {title:'Marcas con identidad propia.',text:'Identidades visuales con un trazo propio y una voz reconocible.'},
        {title:'Experiencias digitales que conectan.',text:'Diseño web y de producto que une tu marca con las personas.'},
        {title:'Diseño que cobra vida.',text:'Movimiento y animación para darle ritmo y carácter a cada idea.'},
      ].map((card,i) => <li key={card.title} className="hp-focus-card" style={brandCardStyle(i)}>
        <div className="hp-focus-card__figure" aria-hidden="true"><GraphicTrace variant={['curl','ring','hook'][i]} duration={850} delay={i*100} cycle={9000}/></div>
        <div className="hp-focus-card__body"><h2>{card.title}</h2><p>{card.text}</p></div>
      </li>)}
    </ul>
  </section>
);

const Logos = () => (
  <section className="hp-logos" aria-label="Clientes">
    <div className="hp-logos__inner">
      <div className="t-eyebrow" style={{ color: 'var(--fg-muted)', textAlign: 'center' }}>
        Trabajamos con marcas que ya decidieron ser memorables
      </div>
      <ul className="hp-logos__row">
        {C.PROJECTS.map((project,i) => (
          <li key={project.slug} className="hp-logos__item">
            {project.slug === 'nacho-books' ? <svg className="hp-logos__mark-svg" viewBox="0 0 160 64" role="img" aria-label={project.client || project.t}>
              <defs><filter id="client-nacho-gray" colorInterpolationFilters="sRGB">
                <feColorMatrix type="matrix" values="0 0 0 0 .65098 0 0 0 0 .65098 0 0 0 0 .65098 -.2126 -.7152 -.0722 1 0"/>
                <feComponentTransfer><feFuncA type="discrete" tableValues="0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"/></feComponentTransfer>
              </filter></defs>
              <image href={project.logo} width="160" height="64" preserveAspectRatio="xMidYMid meet" filter="url(#client-nacho-gray)"/>
            </svg> : project.logo ? <span className="hp-logos__mark" role="img" aria-label={C.CLIENTS[i] || project.client || project.t}
              style={{maskImage:'url("'+project.logo+'")',WebkitMaskImage:'url("'+project.logo+'")'}}/> :
              <span className="hp-logos__fallback">{C.CLIENTS[i] || project.client || project.t}</span>}
          </li>
        ))}
      </ul>
    </div>
  </section>
);

// ──────────────── BAND DIVIDER (animado) ────────────────
const BandDivider = ({ bg = 'yellow', variant = 'horizon', height = 180 }) => (
  <GarabatoBand bg={bg} variant={variant} height={height}/>
);

// ──────────────── MANIFIESTO ────────────────
const Manifesto = () => (
  <section className="hp-manifesto" id="conocenos">

    <SquiggleScatter draw items={[
      { variant: 'curl', color: 'yellow', size: 'xl', top: '22%', left: '5%', rotate: -8, trace: true },
    ]}/>
    <div className="hp-manifesto__inner">
      <div className="t-eyebrow" style={{ color: 'var(--brand-magenta)' }}>Manifiesto</div>
      <p className="hp-manifesto__text">
        Creemos que el diseño pulido<br/>
        muchas veces es <em style={{ fontStyle: 'normal', color: 'var(--brand-magenta)' }}>diseño cobarde</em>.<br/>
        Preferimos un trazo con carácter<br/>
        a una geometría perfecta.
      </p>
      <div className="hp-manifesto__sig">
        <div className="t-caption" style={{ color: 'var(--fg-muted)' }}>Firmado por el equipo · {C.SITE.founded}</div>
      </div>
    </div>
  </section>
);

// ──────────────── TRABAJO ────────────────
const Work = () => {
  const projects = C.PROJECTS;
  const cloudRef = React.useRef(null);
  const cardStrokes=[["curl-yellow",125,-18.5,-20,-25],["ring-magenta",125,-12.5,-25,35],["hook-violet",120,-4,-30,-18],["ring-magenta",120,-16,-35,-65],["curl-yellow",130,-15,-20,90],["hook-violet",120,-4,-25,35],["ring-magenta",120,-16,-30,160],["curl-yellow",130,-15,-35,-100],["hook-violet",120,-4,-20,120],["ring-magenta",120,-16,-25,80],["curl-yellow",130,-15,-30,25],["hook-violet",120,-4,-35,-70],["ring-magenta",120,-16,-20,-135],["curl-yellow",130,-15,-25,150],["hook-violet",120,-4,-30,75],["ring-magenta",120,-16,-35,-25],["curl-yellow",130,-15,-20,-50],["hook-violet",120,-4,-25,170],["ring-magenta",120,-16,-30,120]];
  const projectThemes=React.useMemo(()=>{
    const palette=[
      {background:'#6600ff',text:'#ffffff',family:'violet'},
      {background:'#ffcc00',text:'#0a0a0f',family:'yellow'},
      {background:'#ff0066',text:'#0a0a0f',family:'magenta'},
      {background:'#ff9900',text:'#0a0a0f',family:'orange'}
    ];
    const colorsByBrand={
  "tupublicista": 3,
  "clinica-isis": 0,
  "cultural-bytes": 2,
  "radical-food": 1,
  "guia-e": 0,
  "matrix-events": 0,
  "el-poblado-en-historias": 3,
  "nacho-books": 2,
  "radical-trainer": 3,
  "jml-luxury": 1,
  "fairplay4men": 0,
  "cultural-experience": 1,
  "amara-vidente": 3,
  "the-wormhole-wonders": 0,
  "mindo-los-tucanes": 1,
  "phonics-launch": 3,
  "estudio-retorica": 1,
  "renace-mujer": 2,
  "salud-natural-emit": 0
};
    return projects.map(project=>palette[colorsByBrand[project.slug] ?? 0]);
  }, []);
  React.useEffect(() => {
    const root=cloudRef.current, field=root?.querySelector('.hp-work__grid');
    if(!field) return;
    const cards=[...field.querySelectorAll('.hp-work__float')];
    // Evenly distributed points rotate together through a projected 3D scene.
    const points=cards.map((_,i)=>{
      const y=1-2*(i+.5)/cards.length, radius=Math.sqrt(1-y*y);
      const angle=i*Math.PI*(3-Math.sqrt(5));
      return {x:Math.cos(angle)*radius,y,z:Math.sin(angle)*radius};
    });
    let frame=0,last=0,visible=false,yaw=.45,pitch=-.12,speed=.00021;
    let pointer=null,dragged=false,impulse=0,tiltTarget=-.12;
    let dimensions={width:0,height:0,halfWidth:100,halfHeight:100};
    const enabled=()=>window.GarabatoFX?.isMotionEnabled();
    const measure=()=>{
      dimensions={width:field.clientWidth,height:field.clientHeight,halfWidth:cards[0].offsetWidth/2,halfHeight:cards[0].offsetHeight/2};
      draw();
    };
    const draw=()=>{
      const {width,height,halfWidth,halfHeight}=dimensions;
      const rx=Math.max(1,(width/2-halfWidth-12)/1.045),ry=Math.max(1,(height/2-halfHeight-35)/1.045);
      const cy=Math.cos(yaw),sy=Math.sin(yaw),cp=Math.cos(pitch),sp=Math.sin(pitch);
      cards.forEach((card,i)=>{
        const p=points[i],x=p.x*cy+p.z*sy,z=-p.x*sy+p.z*cy;
        const y=p.y*cp-z*sp,depthZ=p.y*sp+z*cp;
        const perspective=4/Math.max(2.8,4-depthZ),depth=(depthZ+1)/2;
        const px=x*rx*perspective,py=y*ry*perspective;
        const front=Math.max(0,Math.min(1,(depth-.16)/.48));
        const clarity=front*front*(3-2*front);
        const blur=3.5*(1-clarity);
        card.style.left='50%';card.style.top='50%';
        card.style.transform='translate3d('+(px-halfWidth).toFixed(2)+'px,'+(py-halfHeight).toFixed(2)+'px,0)';
        card.style.opacity=(.34+.66*clarity).toFixed(3);
        card.style.filter=blur>.2?'blur('+blur.toFixed(2)+'px)':'none';
        card.style.zIndex=String(Math.round(100+depth*400));
      });
    };
    const tick=time=>{
      frame=0;
      if(visible&&!document.hidden&&enabled()) {
        const dt=last?Math.min(time-last,50):16.67;
        if(!field.contains(document.activeElement)) {
          const blend=1-Math.exp(-dt/650);
          speed+=(.00021+impulse-speed)*blend;
          impulse*=Math.exp(-dt/850);
          if(!pointer) yaw+=speed*dt;
          pitch+=(tiltTarget-pitch)*blend;
          draw();
        }
        last=time;frame=requestAnimationFrame(tick);
      } else last=0;
    };
    const resume=()=>{last=0;draw();if(!frame)frame=requestAnimationFrame(tick);};
    const down=e=>{
      if(!enabled()||!e.isPrimary||e.button!==0) return;
      pointer={id:e.pointerId,x:e.clientX,y:e.clientY,startX:e.clientX,startY:e.clientY};dragged=false;
    };
    const move=e=>{
      if(!enabled())return;
      if(pointer&&pointer.id===e.pointerId) {
        const dx=e.clientX-pointer.x,dy=e.clientY-pointer.y;
        const horizontal=Math.abs(e.clientX-pointer.startX)>Math.abs(e.clientY-pointer.startY);
        if(!dragged&&Math.abs(e.clientX-pointer.startX)>8&&horizontal) {
          dragged=true;root.setPointerCapture(e.pointerId);
          document.activeElement?.blur?.();
        }
        if(dragged) {yaw+=dx*.006;pitch=Math.max(-.4,Math.min(.4,pitch+dy*.002));tiltTarget=pitch;impulse=dx*.000035;draw();}
        pointer.x=e.clientX;pointer.y=e.clientY;
      } else if(e.pointerType==='mouse') {
        const r=root.getBoundingClientRect();
        const nx=(e.clientX-r.left)/r.width-.5;
        impulse=nx*.00006;
        tiltTarget=-.12+((e.clientY-r.top)/r.height-.5)*.12;
      }
    };
    const up=e=>{if(pointer?.id===e.pointerId){pointer=null;if(root.hasPointerCapture(e.pointerId))root.releasePointerCapture(e.pointerId);}};
    const click=e=>{if(dragged){e.preventDefault();e.stopPropagation();dragged=false;}};
    const leave=()=>{if(!pointer){impulse=0;tiltTarget=-.12;}};
    root.addEventListener('pointerdown',down);root.addEventListener('pointermove',move,{passive:true});
    root.addEventListener('pointerup',up);root.addEventListener('pointercancel',up);root.addEventListener('pointerleave',leave);
    root.addEventListener('click',click,true);
    const observer=new IntersectionObserver(entries=>{visible=entries[0].isIntersecting;resume();},{rootMargin:'80px'});
    const resizeObserver=new ResizeObserver(measure);resizeObserver.observe(field);
    window.addEventListener('garabato-motion-change',resume);document.addEventListener('visibilitychange',resume);
    measure();observer.observe(root);
    return()=>{
      cancelAnimationFrame(frame);observer.disconnect();resizeObserver.disconnect();
      root.removeEventListener('pointerdown',down);root.removeEventListener('pointermove',move);root.removeEventListener('pointerup',up);root.removeEventListener('pointercancel',up);root.removeEventListener('pointerleave',leave);root.removeEventListener('click',click,true);
      window.removeEventListener('garabato-motion-change',resume);document.removeEventListener('visibilitychange',resume);
    };
  }, []);

  const darkText = p => p.darkText;
  return (
    <section ref={cloudRef} className="hp-work hp-work--floating hp-work--cloud" id="work">
      <GarabatoAmbient palette="auto" mode="corner" density="low" opacity={0.4}/>
      <div className="hp-work__header">
        <div>
          <div className="t-eyebrow" style={{ color: 'var(--fg-muted)' }}>Trabajo reciente</div>
          <h2 className="t-display-lg" style={{ marginTop: 16 }}>
            Ideas que<br/>
            <em style={{ fontStyle: 'normal', color: 'var(--brand-magenta)' }}>cobran vida</em>.
          </h2>
        </div>
        <div className="hp-work__header-right">
          <p className="t-body-lg" style={{ color: 'var(--fg-muted)', maxWidth: 420 }}>
            Sitios reales, en línea hoy. Cada uno se entrega con capacitación,
            documentación y 30 días de soporte. Siempre.
          </p>
          <a href="portfolio.html" className="btn btn--lg btn--secondary" style={{ marginTop: 24 }}>
            Ver todos los proyectos <Icon name="arrow-right" size={14}/>
          </a>
        </div>
      </div>

      <div className="hp-work__grid">
        {projects.map((p, i) => (
          <div key={p.slug} className={'hp-work__float hp-work__float--'+i}>
          <a className="hp-work-card hp-project-card hp-project-card--brand" href={C.projectUrl(p)} style={{'--project-color':projectThemes[i].background,'--project-text':projectThemes[i].text,'--pattern-angle':(i%3)*35+'deg'}} aria-label={`${p.t}: ${p.tags}`}>
            <div className="hp-project-card__cover">
              <span className="hp-project-card__stroke" aria-hidden="true" style={{'--stroke-src':'url("'+new URL('assets/brand/'+cardStrokes[i][0]+'.svg',document.baseURI).href+'")','--stroke-size':cardStrokes[i][1]+'%','--stroke-left':cardStrokes[i][2]+'%','--stroke-top':cardStrokes[i][3]+'%','--stroke-rotate':cardStrokes[i][4]+'deg'}}/>
            </div>
            <div className="hp-project-card__footer">
              {p.logo ? <img src={p.logo} alt={p.client || p.t} loading="lazy" decoding="async" className={'hp-project-card__logo'+(['matrix-events','radical-trainer','fairplay4men','estudio-retorica','the-wormhole-wonders','phonics-launch'].includes(p.slug)?' hp-project-card__logo--black':'')}/> : <span className="hp-project-card__fallback">{p.short || p.t}</span>}
              <Icon name="arrow-up-right" size={14}/>
            </div>
          </a>
          </div>
        ))}
      </div>
    </section>
  );
};

// ──────────────── NÚMEROS ────────────────
const Numbers = () => (
  <section className="hp-numbers" style={{ background: 'var(--ink-900)' }}>
    <GarabatoAmbient palette="ink" mode="cross" density="low" opacity={0.55}/>
    <SquiggleScatter items={[
      { variant: 'ring', color: 'magenta', size: 'xl', top: '15%', right: '8%', rotate: -10 },
      { variant: 'curl', color: 'yellow', size: 'xxl', bottom: '-15%', left: '-5%', rotate: 10 },
    ]}/>
    <div className="hp-numbers__inner">
      <div className="t-eyebrow" style={{ color: 'var(--brand-yellow)' }}>{C.SITE.yearsLabel[0].toUpperCase() + C.SITE.yearsLabel.slice(1)} años de estudio</div>
      <dl className="hp-numbers__grid">
        {C.NUMBERS.map((x) => (
          <div key={x.label} className="hp-number">
            <dt className="hp-number__label" style={{ order: 2 }}>{x.label}</dt>
            <dd className="hp-number__n" style={{ color: x.c, margin: 0 }}>{x.n}</dd>
          </div>
        ))}
      </dl>
    </div>
  </section>
);

// ──────────────── SERVICIOS ────────────────
const Services = () => <ServiceShowcase/>;

// ──────────────── PROCESO ────────────────
const Process = () => (
  <section className="hp-process" style={{ background: '#fff', color: 'var(--ink-900)' }}>
    <div className="hp-process__inner">
      <div className="t-eyebrow">Cómo trabajamos</div>
      <h2 className="t-display-lg" style={{ marginTop: 16, maxWidth: 900, color: 'var(--ink-900)' }}>
        Un proceso simple.<br/>Con tiempo para pensar.
      </h2>
      <ol className="hp-process__steps">
        {C.PROCESS.map(s => (
          <li key={s.n} className="hp-process-step">
            <div className="hp-process-step__n" style={{ color: 'var(--brand-violet)' }} aria-hidden="true">{s.n}</div>
            <div className="t-h2" style={{ marginTop: 12, color: 'var(--ink-900)' }}>{s.t}</div>
            <p className="t-body-lg" style={{ marginTop: 12, color: 'var(--fg-muted)', maxWidth: 320 }}>{s.d}</p>
          </li>
        ))}
      </ol>
    </div>
  </section>
);

// ──────────────── TESTIMONIOS ────────────────
const Testimonials = () => C.TESTIMONIALS.length === 0 ? null : (
  <section className="hp-testimonials">
    <GarabatoAmbient palette="auto" mode="arc" density="low" opacity={0.45}/>
    <div className="hp-testimonials__inner">
      <div className="t-eyebrow" style={{ color: 'var(--fg-muted)' }}>Lo que dicen</div>
      <div className="hp-testimonials__grid">
        {C.TESTIMONIALS.map((t) => (
          <figure key={t.n} className="hp-testimonial">
            <div className="hp-testimonial__mark" style={{ color: t.c }} aria-hidden="true">"</div>
            <blockquote className="t-h3" style={{ fontWeight: 500 }}>{t.q}</blockquote>
            <figcaption className="hp-testimonial__cite">
              <div className="hp-testimonial__avatar" style={{ background: t.c }} aria-hidden="true">{C.initials(t.n)}</div>
              <div>
                <div className="t-label">{t.n}</div>
                <div className="t-caption">{t.r}</div>
              </div>
            </figcaption>
          </figure>
        ))}
      </div>
    </div>
  </section>
);

// ──────────────── ESTUDIO / EQUIPO ────────────────
const Studio = () => (
  <section className="hp-studio" id="studio">
    <div className="hp-studio__inner">
      <div className="hp-studio__text">
        <div className="t-eyebrow" style={{ color: 'var(--fg-muted)' }}>Estudio</div>
        <h2 className="t-display-lg" style={{ marginTop: 16 }}>
          Somos ocho.<br/>Y un gato.
        </h2>
        <p className="t-body-lg" style={{ color: 'var(--fg-muted)', marginTop: 24 }}>
          Equipo chico, en un mismo estudio de {C.SITE.neighborhood}, {C.SITE.city}, con la calma de
          poder decir que no. Tomamos cinco proyectos por trimestre. Nunca más.
        </p>
        <p className="t-body" style={{ color: 'var(--fg-muted)', marginTop: 20 }}>
          Nos importa que lo que hacemos deje algo atrás: manuales vivos, equipos
          que entienden qué se está construyendo, marcas que pueden seguir
          creciendo sin nosotros.
        </p>
        <div style={{ marginTop: 32, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <a href="studio.html#team" className="btn btn--lg btn--primary">Conocé al equipo <Icon name="arrow-right" size={14}/></a>
          <a href="services.html#process" className="btn btn--lg btn--ghost">Cómo trabajamos</a>
        </div>
      </div>
      <ul className="hp-studio__team">
        {C.TEAM.map((p) => (
          <li key={p.n} className="hp-studio-member">
            <div className="hp-studio-member__avatar" style={{ background: p.c }} aria-hidden="true">
              {p.pet ? <Icon name="smile" size={22} color="#FFD000"/> : C.initials(p.n)}
            </div>
            <div className="t-label">{p.n}</div>
            <div className="t-caption">{p.r}</div>
          </li>
        ))}
      </ul>
    </div>
  </section>
);

// ──────────────── DIARIO ────────────────
const Journal = () => (
  <section className="hp-journal" id="journal">
    <div className="hp-journal__inner">
      <div className="hp-journal__header">
        <div>
          <div className="t-eyebrow" style={{ color: 'var(--fg-muted)' }}>Diario</div>
          <h2 className="t-display-lg" style={{ marginTop: 16 }}>Algo de lo que pensamos.</h2>
        </div>
        <a href="journal.html" className="btn btn--lg btn--secondary">Ver el diario <Icon name="arrow-right" size={14}/></a>
      </div>
      <ol className="hp-journal__list">
        {C.ARTICLES.filter(a => a.home).map((a, i) => (
          <li key={a.slug}>
            <a href={C.articleUrl(a)} className="hp-journal-row" style={{ '--article-accent': articleAccent(a.cat) }}>
              <span className="hp-journal-row__index" aria-hidden="true">{String(i + 1).padStart(2, '0')}</span>
              <div className="hp-journal-row__main">
                <div className="hp-journal-row__category">{a.cat}</div>
                <h3>{a.full || a.t}</h3>
                <p>{a.excerpt}</p>
              </div>
              <div className="hp-journal-row__meta">
                <span>{a.au}</span>
                <time dateTime={a.iso}>{a.date}</time>
              </div>
              <Icon name="arrow-up-right" size={20}/>
            </a>
          </li>
        ))}
      </ol>
    </div>
  </section>
);

// ──────────────── CONTACTO ────────────────
const Contact = () => (
  <section className="hp-contact" id="contact">
    <div className="hp-contact__inner">
      <div className="hp-contact__text">
        <div className="t-eyebrow" style={{ color: 'var(--brand-yellow)' }}>¿Empezamos?</div>
        <h2 className="t-display-lg" style={{ marginTop: 16, color: '#fff' }}>
          Contanos qué<br/>querés construir.
        </h2>
        <p className="t-body-lg" style={{ color: 'rgba(255,255,255,0.84)', marginTop: 24 }}>
          Respondemos en 24 horas hábiles. Si no es una buena idea para nosotros,
          te decimos por qué, y a veces te recomendamos colegas.
        </p>
        <div className="hp-contact__quick">
          <a href={`mailto:${C.SITE.email}`} className="hp-contact__quick-item">
            <Icon name="mail" size={20} color="var(--brand-yellow)"/>
            <div>
              <div className="t-caption" style={{ color: 'rgba(255,255,255,0.8)' }}>Email directo</div>
              <div className="t-h4" style={{ color: '#fff', marginTop: 2 }}>{C.SITE.email}</div>
            </div>
          </a>
          <a href={C.SITE.whatsapp} className="hp-contact__quick-item" target="_blank" rel="noopener noreferrer">
            <Icon name="phone" size={20} color="var(--brand-yellow)"/>
            <div>
              <div className="t-caption" style={{ color: 'rgba(255,255,255,0.8)' }}>WhatsApp</div>
              <div className="t-h4" style={{ color: '#fff', marginTop: 2 }}>{C.SITE.phone}</div>
            </div>
          </a>
          <div className="hp-contact__quick-item">
            <Icon name="home" size={20} color="var(--brand-yellow)"/>
            <div>
              <div className="t-caption" style={{ color: 'rgba(255,255,255,0.8)' }}>Estudio</div>
              <div className="t-h4" style={{ color: '#fff', marginTop: 2 }}>{C.SITE.address}, {C.SITE.neighborhood}, {C.SITE.city}</div>
            </div>
          </div>
        </div>
      </div>
      <ContactForm/>
    </div>
  </section>
);

const FAQ = () => {
  const questions = [
    {
      q: '¿Qué tipo de proyectos desarrolla Garabato?',
      a: 'Creamos identidades digitales, sitios web, tiendas en línea y productos digitales. También acompañamos proyectos de estrategia, diseño y contenido cuando necesitan una visión integral.'
    },
    {
      q: '¿Cómo es el proceso de trabajo?',
      a: 'Empezamos entendiendo el reto y definiendo el alcance. Después avanzamos por etapas de estrategia, diseño y desarrollo, con revisiones contigo en los momentos clave.'
    },
    {
      q: '¿Cuánto tiempo toma un proyecto?',
      a: 'Depende del alcance y de lo que necesite cada proyecto. Acordamos un calendario realista desde el inicio y te contamos qué necesitamos de tu equipo para cumplirlo.'
    },
    {
      q: '¿Trabajan con equipos fuera de Medellín?',
      a: 'Sí. Estamos en Medellín y trabajamos de forma remota con equipos en otras ciudades y países. Organizamos reuniones y entregas para que el proceso sea claro estés donde estés.'
    },
    {
      q: '¿Cómo puedo empezar una conversación?',
      a: 'Cuéntanos un poco sobre tu idea en el formulario. Respondemos en 24 horas hábiles para entender qué necesitas y conversar sobre los siguientes pasos.'
    }
  ];

  return (
    <section className="hp-faq" aria-labelledby="hp-faq-title">
      <div className="hp-faq__inner">
        <div className="hp-faq__intro">
          <div className="t-eyebrow">Preguntas frecuentes</div>
          <h2 className="t-display-lg" id="hp-faq-title">Antes de empezar.</h2>
          <p>Algunas respuestas para que llegues con más claridad a nuestra primera conversación.</p>
        </div>
        <div className="hp-faq__list">
          {questions.map((item, i) => (
            <details className="hp-faq__item" key={item.q}>
              <summary>
                <span className="hp-faq__index" aria-hidden="true">{String(i + 1).padStart(2, '0')}</span>
                <span className="hp-faq__question">{item.q}</span>
                <span className="hp-faq__toggle" aria-hidden="true"/>
              </summary>
              <div className="hp-faq__answer"><p>{item.a}</p></div>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Hero, HeroBullets, Logos, Manifesto, Work, Numbers, Services, Process, Testimonials, Studio, Journal, Contact, FAQ, BandDivider });
