/* ============================================================================
 * Sections.jsx — Secciones de contenido de la página.
 * Cada sección (Método, Trabajo, Nosotros, Contacto) toma sus textos y datos
 * de content.js -> window.BraphoContent. Para cambiar el contenido edita
 * content.js, no este archivo. Aquí vive solo la presentación.
 * ========================================================================== */

const { Button, NodeRule, Input, Textarea } = window.BraphoDesignSystem_df0706 || {};
const C = window.BraphoContent;

/* ===========================================================================
 * MÉTODO
 * ======================================================================== */

function MethodStep({ step, i }) {
  const [ref, on] = useReveal(0.3);
  const ease = 'var(--ease-out)';
  const d = i * 200;
  return (
    <div ref={ref} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 0, height: 12 }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', flex: '0 0 auto', background: i % 2 ? 'var(--node-secondary)' : 'var(--node-primary)', border: '1.5px solid var(--paper-100)', transform: on ? 'scale(1)' : 'scale(0)', transition: 'transform 380ms ' + ease + ' ' + d + 'ms' }} />
        <span style={{ flex: 1, height: 1.5, background: 'var(--paper-100)', transformOrigin: 'left', transform: on ? 'scaleX(1)' : 'scaleX(0)', transition: 'transform 700ms ' + ease + ' ' + (d + 200) + 'ms' }} />
      </div>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--size-label)', color: 'var(--ink-400)', opacity: on ? 1 : 0, transition: 'opacity 500ms ' + ease + ' ' + (d + 280) + 'ms' }}>{'0' + (i + 1)}</span>
      <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 'var(--weight-medium)', fontSize: 'var(--size-h3)', color: 'var(--paper-100)', margin: 0, opacity: on ? 1 : 0, transform: on ? 'none' : 'translateY(10px)', transition: 'opacity 600ms ' + ease + ' ' + (d + 350) + 'ms, transform 600ms ' + ease + ' ' + (d + 350) + 'ms' }}>{step.name}</h3>
      <p style={{ margin: 0, color: 'var(--ink-300)', maxWidth: '30ch', opacity: on ? 1 : 0, transition: 'opacity 600ms ' + ease + ' ' + (d + 500) + 'ms' }}>{step.text}</p>
    </div>
  );
}

/* Ilustración conceptual: una red que se reorganiza. Nodos conectados de forma irregular a la izquierda que, hacia la derecha, se ordenan en una retícula limpia. */
function MethodDiagram() {
  const [ref, on] = useReveal(0.35);
  const ease = 'var(--ease-out)';
  const W = 600, H = 240;
  const rnd = (seed) => { const x = Math.sin(seed * 9301 + 49297) * 233280; return x - Math.floor(x); };
  const rose = 'var(--node-primary)', violet = 'var(--node-secondary)', ink = 'var(--paper-100)';
  const COLS = 10, ROWS = 4, x0 = 30, y0 = 36, dx = (W - 60) / (COLS - 1), dy = (H - 72) / (ROWS - 1);
  // Cada nodo tiene una posición ordenada (retícula) y un desorden proporcional a cuán a la izquierda está.
  const nodes = [];
  for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
    const order = c / (COLS - 1); // 0 izquierda, 1 derecha
    const mess = Math.pow(1 - order, 1.6);
    const i = c * ROWS + r;
    const gx = x0 + c * dx, gy = y0 + r * dy;
    nodes.push({ c, r, gx, gy,
      x: gx + (rnd(i + 1) - 0.5) * dx * 1.6 * mess, y: gy + (rnd(i + 51) - 0.5) * dy * 1.9 * mess,
      size: 3 + (1 - mess) * 1.2 + rnd(i + 101) * 2.2 * mess,
      color: (c + r) % 3 === 0 ? violet : rose, order, mess });
  }
  const at = (c, r) => nodes[c * ROWS + r];
  // Enlaces ordenados: horizontales y verticales de la retícula.
  const links = [];
  for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
    if (c < COLS - 1) links.push([at(c, r), at(c + 1, r)]);
    if (r < ROWS - 1) links.push([at(c, r), at(c, r + 1)]);
  }
  // Enlaces irregulares extra en la zona caótica (diagonales y saltos).
  const chaosLinks = [];
  for (let c = 0; c < COLS - 2; c++) for (let r = 0; r < ROWS; r++) {
    const n = at(c, r);
    if (n.mess > 0.25 && rnd(c * 7 + r + 300) < n.mess) {
      const tc = Math.min(COLS - 1, c + 1 + Math.floor(rnd(c + r + 400) * 2)), tr = Math.floor(rnd(c * 3 + r + 500) * ROWS);
      if (tr !== r) chaosLinks.push([n, at(tc, tr)]);
    }
  }
  // Animación: al entrar, los nodos vienen de una posición aún más dispersa y "asientan"; la línea de orden barre de izquierda a derecha.
  const delay = (n) => Math.round(150 + n.order * 1400);
  const drift = (n, seed) => on ? 'translate(0px,0px)' : 'translate(' + ((rnd(seed) - 0.5) * 90) + 'px,' + ((rnd(seed + 9) - 0.5) * 90) + 'px)';
  return (
    <div ref={ref} style={{ width: '100%' }}>
      <svg viewBox={'0 0 ' + W + ' ' + H} style={{ width: '100%', height: 'auto', display: 'block', overflow: 'visible' }} aria-label="Una red que se reorganiza">
        {chaosLinks.map(([p, q], i) => (
          <line key={'k' + i} x1={p.x} y1={p.y} x2={q.x} y2={q.y} stroke="var(--ink-400)" strokeWidth="1" strokeDasharray="3 5" opacity={on ? 0.8 : 0} style={{ transition: 'opacity 700ms ' + ease + ' ' + (delay(p) + 300) + 'ms' }} />
        ))}
        {links.map(([p, q], i) => (
          <line key={'l' + i} x1={p.x} y1={p.y} x2={q.x} y2={q.y} stroke={ink} strokeWidth={0.7 + q.order * 0.9} opacity={on ? 0.35 + q.order * 0.65 : 0} pathLength="1" strokeDasharray="1" strokeDashoffset={on ? 0 : 1} style={{ transition: 'stroke-dashoffset 800ms ' + ease + ' ' + (delay(p) + 250) + 'ms, opacity 400ms ' + ease + ' ' + (delay(p) + 250) + 'ms' }} />
        ))}
        {nodes.map((n, i) => (
          <circle key={'n' + i} cx={n.x} cy={n.y} r={n.size} fill={n.color} stroke={ink} strokeWidth="1.2" opacity={on ? 1 : 0} style={{ transform: drift(n, i + 700), transition: 'transform 1000ms ' + ease + ' ' + delay(n) + 'ms, opacity 500ms ' + ease + ' ' + delay(n) + 'ms' }} />
        ))}
      </svg>
    </div>
  );
}

function Method() {
  const { label, title, cta, steps } = C.method;
  const cols = useCols([[860, 3], [0, 1]]);
  return (
    <Section id="metodo" label={label} tone="ink">
      <Reveal style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(min(100%,320px),1fr))', gap: 'clamp(24px,5vw,80px)', alignItems: 'center', paddingBottom: 'clamp(40px,5vw,64px)' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', alignItems: 'flex-start' }}>
          <h2 style={{ fontSize: 'var(--size-h2)', fontWeight: 'var(--weight-medium)', maxWidth: '16ch', color: 'var(--paper-100)', margin: 0 }}>{title}</h2>
          <Button variant="inverse" onClick={() => scrollToId(cta.target)}>{cta.label}</Button>
        </div>
        <MethodDiagram />
      </Reveal>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(' + cols + ',minmax(0,1fr))', gap: 'clamp(36px,4vw,40px)', paddingTop: 'clamp(32px,4vw,48px)', borderTop: '1px solid var(--ink-600)' }}>
        {steps.map((m, i) => <MethodStep key={m.name} step={m} i={i} />)}
      </div>
    </Section>
  );
}

/* ===========================================================================
 * NUESTRO TRABAJO
 * ======================================================================== */

// Imagen de un proyecto: usa la imagen indicada en content.js, o un espacio
// para arrastrar una imagen cuando el campo `image` está vacío.
function WorkImage({ project }) {
  return (
    <div style={{ aspectRatio: '16 / 10', width: '100%', position: 'relative' }}>
      <image-slot id={project.id} src={project.image || undefined} shape="rounded" radius="3" placeholder={'Captura: ' + project.title}></image-slot>
    </div>
  );
}

// Carrusel del portafolio de proyectos.
function Portfolio() {
  const projects = C.work.projects;
  const [i, setI] = React.useState(0);
  const n = projects.length;
  const go = (d) => setI((v) => (v + d + n) % n);
  const current = projects[i];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(min(100%,320px),1fr))', gap: 'clamp(32px,5vw,72px)', alignItems: 'stretch' }}>
      <div style={{ position: 'relative', overflow: 'hidden', border: '1.5px solid var(--line-rule)', borderRadius: 'var(--radius-md)', background: 'var(--paper-200)', backgroundImage: 'var(--grid-paper)' }}>
        <div style={{ display: 'flex', width: n * 100 + '%', height: '100%', transform: 'translateX(-' + (i * 100 / n) + '%)', transition: 'transform 600ms var(--ease-out)' }}>
          {projects.map((p) => (
            <div key={p.id} style={{ width: 100 / n + '%', flex: '0 0 auto', padding: 'clamp(16px,2.5vw,28px)' }}>
              <WorkImage project={p} />
            </div>
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 'var(--space-6)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-5)', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {projects.map((p, k) => (
              <button key={p.id} aria-label={'Ir al proyecto ' + (k + 1)} onClick={() => setI(k)} style={{ width: 11, height: 11, borderRadius: '50%', padding: 0, cursor: 'pointer', border: '1.5px solid var(--ink-800)', background: k === i ? (k % 2 ? 'var(--node-secondary)' : 'var(--node-primary)') : 'transparent', transition: 'var(--transition-ui)' }} />
            ))}
          </div>
          <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
            <Button size="sm" variant="secondary" aria-label="Anterior" onClick={() => go(-1)} style={{ padding: '8px 10px' }}><i data-lucide="arrow-left" style={{ width: 16, height: 16 }}></i></Button>
            <Button size="sm" variant="secondary" aria-label="Siguiente" onClick={() => go(1)} style={{ padding: '8px 10px' }}><i data-lucide="arrow-right" style={{ width: 16, height: 16 }}></i></Button>
          </div>
        </div>
        <div>
          <p style={{ fontSize: 'var(--size-small)', color: 'var(--ink-400)', margin: '0 0 var(--space-3)' }}>Ya en operación</p>
          <p style={{ fontFamily: 'var(--font-serif)', fontSize: 'var(--size-h3)', fontWeight: 'var(--weight-medium)', color: 'var(--text-strong)', margin: '0 0 var(--space-3)', lineHeight: 'var(--leading-snug)', maxWidth: '26ch' }}>{current.title}</p>
          <p style={{ margin: 0, color: 'var(--ink-600)', maxWidth: '40ch' }}>{current.description}</p>
        </div>
      </div>
    </div>
  );
}

function GrowthStep({ step, i }) {
  const [ref, on] = useReveal(0.3);
  const ease = 'var(--ease-out)';
  const d = i * 200;
  const color = i === 1 ? 'var(--node-secondary)' : 'var(--node-primary)';
  return (
    <div ref={ref} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 0, height: 14 }}>
        <span style={{ width: 8 + i * 3, height: 8 + i * 3, borderRadius: '50%', flex: '0 0 auto', background: color, border: '1.5px solid var(--ink-800)', transform: on ? 'scale(1)' : 'scale(0)', transition: 'transform 420ms ' + ease + ' ' + d + 'ms' }} />
        <span style={{ flex: 1, height: 1.5, background: 'var(--ink-800)', transformOrigin: 'left', transform: on ? 'scaleX(1)' : 'scaleX(0)', transition: 'transform 700ms ' + ease + ' ' + (d + 200) + 'ms' }} />
      </div>
      <span style={{ fontSize: 'var(--size-small)', color: 'var(--ink-400)', opacity: on ? 1 : 0, transition: 'opacity 500ms ' + ease + ' ' + (d + 150) + 'ms' }}>{step.name}</span>
      <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 'var(--weight-medium)', fontSize: 'var(--size-h3)', color: 'var(--text-strong)', margin: 0, maxWidth: '22ch', opacity: on ? 1 : 0, transform: on ? 'none' : 'translateY(10px)', transition: 'opacity 600ms ' + ease + ' ' + (d + 250) + 'ms, transform 600ms ' + ease + ' ' + (d + 250) + 'ms' }}>{step.title}</h3>
      <p style={{ margin: 0, color: 'var(--ink-600)', maxWidth: '34ch', opacity: on ? 1 : 0, transition: 'opacity 600ms ' + ease + ' ' + (d + 400) + 'ms' }}>{step.text}</p>
    </div>
  );
}

function Work() {
  const { label, title, intro, growth } = C.work;
  const cols = useCols([[860, 3], [0, 1]]);
  return (
    <Section id="trabajo" label={label} node="secondary" title={title} wide intro={intro}>
      <Reveal><Portfolio /></Reveal>
      <div style={{ marginTop: 'clamp(56px,7vw,96px)', paddingTop: 'clamp(32px,4vw,48px)', borderTop: '1px solid var(--paper-300)', display: 'grid', gridTemplateColumns: 'repeat(' + cols + ',minmax(0,1fr))', gap: 'clamp(36px,4vw,48px)' }}>
        {growth.map((g, i) => <GrowthStep key={g.name} step={g} i={i} />)}
      </div>
    </Section>
  );
}

/* ===========================================================================
 * NOSOTROS
 * ======================================================================== */

// Tarjeta de persona: cuadro con retícula y, dentro, la foto circular.
// La foto usa `photoSrc` (ruta/URL) o, si está vacío, un espacio para
// arrastrar la imagen (`slotId`). En pantallas anchas alterna lado con
// `reverse`; en móvil se apila y la imagen se centra.
function PersonCard({ name, role, note, photoSrc, slotId, accent = 'var(--node-primary)', reverse = false }) {
  const [wide, setWide] = React.useState(() => window.innerWidth >= 700);
  React.useEffect(() => {
    const fn = () => setWide(window.innerWidth >= 700);
    fn(); window.addEventListener('resize', fn);
    return () => window.removeEventListener('resize', fn);
  }, []);
  const flip = reverse && wide;
  // Círculo de la foto: 85% del cuadro (deja un pequeño margen con el borde).
  const circle = { width: '85%', aspectRatio: '1', borderRadius: '50%', border: '3px solid ' + accent, overflow: 'hidden', background: 'var(--paper-100)', position: 'relative', flex: '0 0 auto' };
  const frame = (
    // justifySelf: en escritorio a la izquierda; en móvil centrado.
    <div style={{ position: 'relative', aspectRatio: '1', width: '100%', maxWidth: 240, border: '1.5px solid var(--line-rule)', borderRadius: 'var(--radius-md)', overflow: 'hidden', background: 'var(--paper-100)', backgroundImage: 'var(--grid-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', justifySelf: wide ? 'start' : 'center' }}>
      <div style={circle}>
        {photoSrc
          ? <img src={photoSrc} alt={name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          : slotId
            ? React.createElement('image-slot', { id: slotId, shape: 'circle', placeholder: 'Foto de ' + name })
            : null}
      </div>
    </div>
  );
  const info = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
        <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 'var(--size-h3)', fontWeight: 'var(--weight-medium)', margin: 0, color: 'var(--text-strong)' }}>{name}</h3>
        {role && <p style={{ margin: 0, fontSize: 'var(--size-small)', color: 'var(--text-muted)' }}>{role}</p>}
      </div>
      {note && <p style={{ margin: 0, color: 'var(--ink-600)' }}>{note}</p>}
    </div>
  );
  return (
    <div style={{ display: 'grid', gridTemplateColumns: wide ? (flip ? 'minmax(0,1fr) minmax(0,240px)' : 'minmax(0,240px) minmax(0,1fr)') : 'minmax(0,1fr)', gap: 'clamp(24px,5vw,64px)', alignItems: wide ? 'center' : 'start' }}>
      {flip ? <React.Fragment>{info}{frame}</React.Fragment> : <React.Fragment>{frame}{info}</React.Fragment>}
    </div>
  );
}

function About() {
  const { label, title, intro, people } = C.about;
  return (
    <Section id="nosotros" label={label} title={title} tone="raised" introFull intro={intro}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'clamp(48px,6vw,80px)' }}>
        {people.map((p, i) => (
          <React.Fragment key={p.id}>
            {/* Línea separadora antes de cada perfil (incluido el primero). */}
            <NodeRule animate startColor="var(--node-secondary)" endColor="var(--node-primary)" />
            <Reveal delay={i * 140}>
              <PersonCard
                name={p.name}
                role={p.role}
                note={p.bio}
                photoSrc={p.photo || undefined}
                slotId={'photo-' + p.id}
                accent={accentVar(p.accent)}
                reverse={i % 2 === 1}
              />
            </Reveal>
          </React.Fragment>
        ))}
      </div>
    </Section>
  );
}

/* ===========================================================================
 * CONTACTO
 * ======================================================================== */

function Contact() {
  const c = C.contact;
  const [sent, setSent] = React.useState(false);
  return (
    <Section id="contacto" label={c.label} node="secondary">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(min(100%,300px),1fr))', gap: 'clamp(40px,7vw,112px)', alignItems: 'start' }}>
        <Reveal>
          <h2 style={{ fontSize: 'var(--size-h2)', fontWeight: 'var(--weight-medium)', maxWidth: '16ch', marginBottom: 'var(--space-5)' }}>{c.title}</h2>
          <p style={{ color: 'var(--ink-600)', maxWidth: '38ch', fontSize: 'var(--size-body-lg)', marginBottom: 'var(--space-7)' }}>{c.text}</p>
          <NodeRule animate style={{ maxWidth: 220, marginBottom: 'var(--space-6)' }} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
            <a href={'mailto:' + c.email} style={{ color: 'var(--ink-800)', borderBottom: '1px solid var(--paper-400)', width: 'fit-content', fontSize: 'var(--size-body-lg)' }}>{c.email}</a>
            <span style={{ color: 'var(--ink-400)', fontSize: 'var(--size-small)' }}>{c.location}</span>
          </div>
        </Reveal>
        <Reveal delay={120}>
          {sent ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)', padding: 'var(--space-7)', background: 'var(--paper-200)', borderRadius: 'var(--radius-md)' }}>
              <NodeRule style={{ maxWidth: 120 }} />
              <p style={{ margin: 0, fontFamily: 'var(--font-serif)', fontSize: 'var(--size-h3)', color: 'var(--text-strong)' }}>{c.success.title}</p>
              <p style={{ margin: 0, color: 'var(--ink-600)' }}>{c.success.text}</p>
            </div>
          ) : (
            <form onSubmit={(e) => { e.preventDefault(); setSent(true); }} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)', padding: 'clamp(24px,3vw,40px)', background: 'var(--paper-200)', borderRadius: 'var(--radius-md)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(min(100%,180px),1fr))', gap: 'var(--space-4)' }}>
                <Input variant="box" label={c.form.name.label} placeholder={c.form.name.placeholder} />
                <Input variant="box" label={c.form.email.label} type="email" placeholder={c.form.email.placeholder} />
              </div>
              <Input variant="box" label={c.form.business.label} placeholder={c.form.business.placeholder} />
              <Textarea variant="box" label={c.form.message.label} rows={4} placeholder={c.form.message.placeholder} />
              <Button type="submit" size="lg" style={{ justifyContent: 'center' }}>{c.form.submit}</Button>
            </form>
          )}
        </Reveal>
      </div>
    </Section>
  );
}

Object.assign(window, { Method, Work, About, Contact });
