// ProblemSection — "El Problema Operativo"
// Structural pattern inspired by the reference: split left(title+copy) / right(soft-halo framed card).
// 3 rows stacked, each with its own original diagrammatic visual inside the card.
// All original artwork; no branded logos or proprietary patterns.

const { useReveal, Tilt, Reveal, GlowCard } = window;

function ProblemSection({ root }) {
  const isMobile = window.useIsMobile();
  const items = [
  {
    n: '01',
    title: 'Sobrestock sin visibilidad',
    body: 'Los establecimientos carecen de sistemas que identifiquen productos en riesgo inminente, resultando en reposiciones ineficientes.',
    side: 'right',
    glowColor: 'orange',
    visual: <ShelfInventory />
  },
  {
    n: '02',
    title: 'Desequilibrio oferta-demanda',
    body: 'Herramientas de predicción costosas y lentas para empresas de escala media o con baja digitalización.',
    side: 'left',
    glowColor: 'blue',
    visual: <SupplyDemandChart />
  },
  {
    n: '03',
    title: 'Procesos fragmentados',
    body: 'Falta de automatización en descuentos y conexión directa con ONGs para la donación de excedentes.',
    side: 'right',
    glowColor: 'purple',
    visual: <FragmentedFlow />
  }];


  return (
    <section id="problema" style={{
      position: 'relative',
      padding: isMobile ? '36px 20px 36px' : '48px 32px 48px',
      background: '#ffffff',
      scrollMarginTop: 80
    }}>
      {/* Section intro */}
      <Reveal root={root}>
        <div style={{ maxWidth: 1080, margin: isMobile ? '0 auto 24px' : '0 auto 40px' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
            letterSpacing: 1.5, textTransform: 'uppercase', opacity: 0.5, marginBottom: 18
          }}>◇ El Problema Operativo</div>
          <h2 style={{
            letterSpacing: '-0.045em',
            lineHeight: 0.98, margin: 0, fontWeight: 400, maxWidth: 900, fontSize: "30px"
          }}>
            Hoy, el excedente alimentario <em style={{ fontFamily: 'Instrument Serif, serif' }}>se gestiona a ciegas</em>.
          </h2>
        </div>
      </Reveal>

      <div style={{
        maxWidth: 1120, margin: '0 auto',
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
        gap: isMobile ? 20 : 18,
        alignItems: 'stretch'
      }}>
        {items.map((it, i) =>
        <ProblemCard key={i} root={root} item={it} index={i} />
        )}
      </div>
    </section>);

}

function ProblemCard({ root, item, index }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column',
      gap: 20
    }}>
      <VisualCol shown={true} fromRight={false} glowColor={item.glowColor}>{item.visual}</VisualCol>
      <TextCol item={item} shown={true} fromRight={false} />
    </div>);

}

function TextCol({ item, shown, fromRight }) {
  return (
    <div style={{ padding: '8px 4px 0', maxWidth: '100%' }}>
      <div style={{
        fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
        letterSpacing: 1.5, opacity: 0.45, marginBottom: 24
      }}>{item.n} · {String(item.title).toUpperCase()}</div>
      <h3 style={{
        fontSize: 'clamp(22px, 1.8vw, 28px)', lineHeight: 1.1, letterSpacing: '-0.025em',
        margin: '0 0 14px', fontWeight: 400
      }}>{item.title}</h3>
      <p style={{
        fontSize: 15, lineHeight: 1.55, color: '#333',
        margin: 0, textWrap: 'pretty'
      }}>{item.body}</p>
    </div>);

}

// The framed card with soft halo border — original stylistic interpretation.
function VisualCol({ children, shown, fromRight, glowColor = 'blue' }) {
  return (
    <div style={{ width: '100%' }}>
      <GlowCard
        glowColor={glowColor}
        radius={24}
        border={2}
        style={{
          width: '100%', aspectRatio: '1.1 / 1',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}
        innerStyle={{
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 40
        }}>
        
        <div style={{
          width: '100%', height: '100%',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          {React.Children.map(children, (child) =>
          React.isValidElement(child) ? React.cloneElement(child, { shown: true }) : child
          )}
        </div>
      </GlowCard>
    </div>);

}

// ── Visual 01: Precarious stack with falling apple ──────────────
function ShelfInventory({ shown = false }) {
  // Entrance: apples drop into the stack one-by-one (wobble), then the top apple
  // detaches and falls in an arc. Idle: continues to sway very subtly.
  const T = (delay, dur = 900) =>
  `all ${dur}ms cubic-bezier(.2,.7,.1,1) ${delay}ms`;

  // Stack apples: sorted bottom → top, each with its own (cx, cy, rx, ry, delay)
  const apples = [
  { cx: 135, cy: 315, rx: 32, ry: 30, d: 0 },
  { cx: 200, cy: 318, rx: 34, ry: 30, d: 80 },
  { cx: 265, cy: 314, rx: 32, ry: 30, d: 160 },
  { cx: 168, cy: 256, rx: 31, ry: 29, d: 280 },
  { cx: 232, cy: 258, rx: 32, ry: 29, d: 360 },
  { cx: 200, cy: 198, rx: 30, ry: 28, d: 480 }];


  return (
    <svg viewBox="0 0 400 400" width="100%" height="100%" style={{ maxWidth: 420 }}>
      <defs>
        <radialGradient id="p1-accent" cx="50%" cy="45%" r="55%">
          <stop offset="0" stopColor="#e8a07b" stopOpacity="0.9" />
          <stop offset="1" stopColor="#e8a07b" stopOpacity="0.65" />
        </radialGradient>
      </defs>

      {/* Ground line */}
      <line x1="60" y1="340" x2="340" y2="340"
      stroke="#0a0a0a" strokeOpacity={shown ? 0.18 : 0} strokeWidth="1"
      style={{ transition: T(0, 700) }} />

      {/* Stack apples — each drops in from above with individual delay */}
      <g stroke="#0a0a0a" strokeWidth="1.3" fill="none" strokeLinecap="round">
        {apples.map((a, i) =>
        <g key={i} style={{
          opacity: shown ? 1 : 0,
          transform: shown ? 'translate3d(0, 0px, 0)' : 'translate3d(0, -40px, 0)',
          transition: T(a.d, 700)
        }}>
            <ellipse cx={a.cx} cy={a.cy} rx={a.rx} ry={a.ry} />
          </g>
        )}
        {/* Stem on top apple, appears slightly after */}
        <g style={{ opacity: shown ? 1 : 0, transition: T(700, 400) }}>
          <path d="M200 170 q3 -14 14 -20" />
          <path d="M210 155 q6 -3 8 -9" strokeOpacity="0.7" />
        </g>
      </g>

      {/* Falling apple — starts near top of stack, arcs out and down.
                   Uses a CSS-animated <g> with keyframes for the arc. */}
      <g className="odas-fall-apple"
      style={{
        opacity: shown ? 1 : 0,
        transition: `opacity 300ms ease ${shown ? 1000 : 0}ms`
      }}>
        <g transform="translate(200, 170)">
          <g className="odas-fall-inner">
            <ellipse cx="0" cy="0" rx="26" ry="24" fill="url(#p1-accent)" />
            <path d="M-4 -24 q2 -10 10 -14" stroke="#0a0a0a" strokeWidth="1.3" fill="none" strokeLinecap="round" />
          </g>
        </g>
      </g>

      {/* Motion trail dots — fade in sequentially after the apple falls */}
      <g fill="#0a0a0a">
        <circle cx="230" cy="158" r="1.4" style={{ opacity: shown ? 0.45 : 0, transition: T(1100, 400) }} />
        <circle cx="255" cy="148" r="1.1" style={{ opacity: shown ? 0.35 : 0, transition: T(1200, 400) }} />
        <circle cx="278" cy="144" r="0.9" style={{ opacity: shown ? 0.25 : 0, transition: T(1300, 400) }} />
      </g>

      <text x="60" y="378" fontSize="9" fontFamily="JetBrains Mono, monospace"
      fill="#0a0a0a" opacity={shown ? 0.35 : 0} letterSpacing="2"
      style={{ transition: T(900, 500) }}>
        I. EXCEDENTE
      </text>

      <style>{`
        .odas-fall-apple .odas-fall-inner {
          transform-origin: 0 0;
          animation: odas-apple-arc 2.6s cubic-bezier(.35,0,.65,1) 1s forwards;
        }
        @keyframes odas-apple-arc {
          0%   { transform: translate(0, 0) rotate(0deg); opacity: 1; }
          45%  { transform: translate(70px, -10px) rotate(25deg); opacity: 1; }
          100% { transform: translate(135px, 155px) rotate(70deg); opacity: 0; }
        }
      `}</style>
    </svg>);

}

// ── Visual 02: Two waves, out of phase ─────────────────────────
function SupplyDemandChart({ shown = false }) {
  const wave = (phase, amp, yoff, freq = 2.0) => {
    const out = [];
    for (let x = 0; x <= 340; x += 3) {
      const y = yoff +
      Math.sin(x / 340 * Math.PI * freq + phase) * amp +
      Math.sin(x / 340 * Math.PI * freq * 2.3 + phase * 1.3) * amp * 0.18;
      out.push(`${x + 30},${y.toFixed(2)}`);
    }
    return out.join(' ');
  };
  const L = 900; // path length upper bound for draw-in effect
  return (
    <svg viewBox="0 0 400 400" width="100%" height="100%" style={{ maxWidth: 440 }}>
      <ellipse cx="200" cy="215" rx="60" ry="22"
      fill="#e8a07b"
      className={shown ? 'odas-pulse' : ''}
      style={{ opacity: shown ? 0.22 : 0, transition: 'opacity 800ms ease 1100ms' }} />

      <polyline fill="none" stroke="#0a0a0a" strokeWidth="1.8"
      strokeLinejoin="round" strokeLinecap="round"
      points={wave(0.2, 58, 200)}
      style={{
        strokeDasharray: L,
        strokeDashoffset: shown ? 0 : L,
        transition: 'stroke-dashoffset 1800ms cubic-bezier(.4,0,.2,1) 200ms'
      }} />

      <polyline fill="none" stroke="#0a0a0a" strokeOpacity="0.35" strokeWidth="1.4"
      strokeLinejoin="round" strokeLinecap="round"
      points={wave(2.6, 52, 210)}
      style={{
        strokeDasharray: L,
        strokeDashoffset: shown ? 0 : L,
        transition: 'stroke-dashoffset 1800ms cubic-bezier(.4,0,.2,1) 500ms'
      }} />

      <g style={{
        transformOrigin: '198px 215px',
        transform: shown ? 'scale(1)' : 'scale(0)',
        transition: 'transform 500ms cubic-bezier(.5,1.6,.5,1) 1600ms'
      }}>
        <circle cx="198" cy="215" r="3" fill="#0a0a0a" />
        <circle cx="198" cy="215" r="9" fill="none" stroke="#0a0a0a" strokeOpacity="0.3" />
      </g>

      <line x1="30" y1="205" x2="370" y2="205"
      stroke="#0a0a0a" strokeOpacity={shown ? 0.08 : 0} strokeWidth="1" strokeDasharray="1 5"
      style={{ transition: 'stroke-opacity 700ms ease 100ms' }} />

      <text x="30" y="378" fontSize="9" fontFamily="JetBrains Mono, monospace"
      fill="#0a0a0a" opacity={shown ? 0.35 : 0} letterSpacing="2"
      style={{ transition: 'opacity 500ms ease 1800ms' }}>
        II. DESFASE
      </text>

      <style>{`
        .odas-pulse { animation: odas-pulse-kf 4s ease-in-out 2s infinite; }
        @keyframes odas-pulse-kf {
          0%, 100% { opacity: 0.22; }
          50%      { opacity: 0.35; }
        }
      `}</style>
    </svg>);

}

// ── Visual 03: Falling crates / tumbling stack ──────────────
function FragmentedFlow() {
  // Stacked crates at bottom-left (in order, drawn back-to-front)
  // Each crate: { x, y, w, h }
  const stack = [
    { x: 60,  y: 290, w: 230, h: 32 }, // bottom long base
    { x: 75,  y: 250, w: 180, h: 32 }, // middle
    { x: 95,  y: 210, w: 130, h: 32 }, // upper
    { x: 75,  y: 168, w: 110, h: 32 }, // top-left small
  ];
  // Two tumbling crates upper-right
  const falling = [
    { cx: 265, cy: 145, w: 100, h: 36, rot: 18 },
    { cx: 305, cy: 75,  w: 90,  h: 32, rot: -12 },
  ];

  return (
    <svg viewBox="0 0 400 400" width="100%" height="100%" style={{ maxWidth: 440 }}>
      {/* Ground line */}
      <line x1="40" y1="328" x2="360" y2="328"
        stroke="#0a0a0a" strokeOpacity="0.18" strokeWidth="1" />

      {/* Stacked crates — outlined, with cross/diagonal lines for "crate" texture */}
      <g stroke="#0a0a0a" strokeWidth="1.3" fill="#fffdf8" strokeLinecap="round" strokeLinejoin="round">
        {stack.map((c, i) => (
          <g key={i}>
            <rect x={c.x} y={c.y} width={c.w} height={c.h} />
            {/* Subtle diagonal cross-stitch for crate feel */}
            <line x1={c.x} y1={c.y} x2={c.x + c.w} y2={c.y + c.h} strokeOpacity="0.18" />
          </g>
        ))}
      </g>

      {/* Two tumbling crates upper-right */}
      <g stroke="#0a0a0a" strokeWidth="1.3" fill="#fffdf8" strokeLinecap="round" strokeLinejoin="round">
        {falling.map((c, i) => (
          <g key={i} transform={`translate(${c.cx} ${c.cy}) rotate(${c.rot})`}>
            <rect x={-c.w / 2} y={-c.h / 2} width={c.w} height={c.h}
              fill={i === 0 ? '#fffdf8' : '#fdeadd'} />
            <line x1={-c.w / 2} y1={-c.h / 2} x2={c.w / 2} y2={c.h / 2} strokeOpacity="0.18" />
          </g>
        ))}
      </g>

      {/* Motion dots trailing the falling crates */}
      <g fill="#0a0a0a" opacity="0.35">
        <circle cx="240" cy="170" r="1.4" />
        <circle cx="225" cy="195" r="1.1" />
        <circle cx="282" cy="105" r="1.2" />
      </g>

      {/* Accent halo behind the topmost falling crate */}
      <circle cx="305" cy="75" r="40" fill="#e8a07b" opacity="0.14" />

      <text x="40" y="360" fontSize="10" fontFamily="JetBrains Mono, monospace"
        fill="#0a0a0a" opacity="0.45" letterSpacing="1.5">
        FLUJO INTERRUMPIDO
      </text>
      <text x="40" y="378" fontSize="9" fontFamily="JetBrains Mono, monospace"
        fill="#0a0a0a" opacity="0.3" letterSpacing="2">
        III. FRAGMENTADO
      </text>
    </svg>
  );
}

Object.assign(window, { ProblemSection });