/* Problem scene — choreographed chaos → order.
   1. Tags drift around the canvas with subtle rotation/jitter (chaos)
   2. When the section enters view, a "scanning" coral beam crosses
   3. Everything freezes mid-drift (suspension)
   4. Snap-align: tags lock into orbit around the centre with a coral pulse,
      lines draw from centre outward (BODE captures them)
*/

const SYSTEMS = [
  { name: "Finance",             angle: -90 },
  { name: "Energy Management",   angle: -38 },
  { name: "Property Management", angle:  18 },
  { name: "Customer Experience", angle:  74 },
  { name: "Short Stay / BTR",    angle: 130 },
  { name: "CRM",                 angle: 196 },
];

function Systems() {
  const ref = React.useRef(null);
  const [phase, setPhase] = React.useState('chaos'); // chaos → scan → freeze → lock
  const tagsRef = React.useRef([]);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) { setPhase('lock'); return; }

    const trigger = ScrollTrigger.create({
      trigger: el,
      start: 'top 65%',
      once: true,
      onEnter: () => {
        // chaos already running — start scan, then freeze, then lock
        setPhase('scan');
        setTimeout(() => setPhase('freeze'), 700);
        setTimeout(() => setPhase('lock'), 950);
      },
    });
    return () => trigger.kill();
  }, []);

  // Generate randomised "chaos positions" so each tag wanders independently
  const chaosPositions = React.useMemo(() => SYSTEMS.map((_, i) => ({
    x: 10 + Math.random() * 70,                  // %
    y: 8 + Math.random() * 70,
    rot: (Math.random() - 0.5) * 6,
    drift: 3 + Math.random() * 4,                // s — duration variance
    delay: -Math.random() * 4,
  })), []);

  // Container is forced square (via CSS aspect-ratio) so the SVG's 100×100
  // viewBox matches container percentages — lines drawn from (50,50) to a
  // point on the orbit land exactly at the absolutely-positioned tags.
  const ORBIT = 36;

  return (
    <div className={`systems systems--${phase}`} ref={ref}>
      {/* Centre node — dot positioned at true (50%,50%); label sits below
          on its own absolute position so it doesn't push the dot off-centre. */}
      <span className="systems__core-pulse" aria-hidden="true"></span>
      <span className="systems__core-dot" aria-hidden="true"></span>
      <span className="systems__core-label">BODE · ONE LAYER</span>

      {/* Scanning beam — only present during scan phase */}
      {phase === 'scan' && <div className="systems__scan" />}

      {/* Connector lines — drawn outward from centre on lock. preserveAspectRatio
          stays default ("xMidYMid meet"); container is square so it fits cleanly. */}
      <svg className="systems__lines" viewBox="0 0 100 100">
        {SYSTEMS.map((s, i) => {
          const rad = (s.angle * Math.PI) / 180;
          const ox = 50 + Math.cos(rad) * ORBIT;
          const oy = 50 + Math.sin(rad) * ORBIT;
          // Draw the line only after lock by animating stroke-dashoffset from
          // the line's full length down to 0 (no pathLength tricks needed).
          const dx = ox - 50, dy = oy - 50;
          const len = Math.sqrt(dx * dx + dy * dy);
          return (
            <line
              key={i}
              className="systems__line"
              x1="50" y1="50"
              x2={ox} y2={oy}
              stroke="#E8513A"
              strokeWidth="0.4"
              strokeLinecap="round"
              strokeDasharray={len}
              style={{
                strokeDashoffset: phase === 'lock' ? 0 : len,
                transitionDelay: `${0.1 + i * 0.07}s`,
              }}
            />
          );
        })}
      </svg>

      {/* Tags */}
      {SYSTEMS.map((s, i) => {
        const chaos = chaosPositions[i];
        // Lock position: orbital coordinates around centre
        const r = 36;
        const rad = (s.angle * Math.PI) / 180;
        const lockX = 50 + Math.cos(rad) * r;
        const lockY = 50 + Math.sin(rad) * r;

        const style =
          phase === 'lock'
            ? {
                left: `${lockX}%`, top: `${lockY}%`,
                transform: `translate(-50%, -50%) rotate(0deg)`,
                transitionDelay: `${0.05 + i * 0.05}s`,
                animation: 'none',
              }
            : phase === 'freeze'
            ? {
                left: `${chaos.x}%`, top: `${chaos.y}%`,
                transform: `translate(-50%, -50%) rotate(${chaos.rot}deg)`,
                animation: 'none',
                transitionDuration: '0.18s',
              }
            : {
                left: `${chaos.x}%`, top: `${chaos.y}%`,
                animation: `chaos-drift ${chaos.drift}s ease-in-out ${chaos.delay}s infinite, chaos-flicker 2.4s steps(8) ${chaos.delay}s infinite`,
              };

        return (
          <div
            key={s.name}
            ref={(n) => (tagsRef.current[i] = n)}
            className={`system-tag ${phase === 'lock' ? 'connected' : ''} ${phase === 'freeze' ? 'frozen' : ''}`}
            style={style}
          >
            <span>{s.name}</span>
            <span className="br tl"></span>
            <span className="br tr"></span>
            <span className="br bl"></span>
            <span className="br br_"></span>
          </div>
        );
      })}

      <style>{`
        @keyframes chaos-drift {
          0%   { transform: translate(-50%, -50%) translate(0,0) rotate(-2deg); }
          25%  { transform: translate(-50%, -50%) translate(8px,-6px) rotate(1deg); }
          50%  { transform: translate(-50%, -50%) translate(-4px,10px) rotate(2deg); }
          75%  { transform: translate(-50%, -50%) translate(6px,4px) rotate(-1deg); }
          100% { transform: translate(-50%, -50%) translate(0,0) rotate(-2deg); }
        }
        @keyframes chaos-flicker {
          0%, 90%, 100% { opacity: 1; }
          92% { opacity: 0.55; }
          94% { opacity: 1; }
          96% { opacity: 0.7; }
        }
      `}</style>
    </div>
  );
}

function Problem() {
  return (
    <section id="problem" className="section problem" data-screen-label="02 Problem">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow"><span className="num">02</span> <span className="bar"></span> The Problem</div>
        </div>
        <h2 className="problem__quote reveal">
          No AI middleware<br/>
          in the market<br/>
          <span className="em">today<span className="bode-stop"></span></span>
        </h2>
        <blockquote className="problem__pull reveal">
          <span className="problem__pull-mark" aria-hidden="true">“</span>
          Your business is spread across countless platforms.<br/>
          <span className="problem__pull-em">None of them talk to each other.</span>
        </blockquote>
        <div className="problem__copy problem__copy--two-col reveal">
          <p>Property owners and operators must currently interact manually with separate systems for finance, energy management, property management, customer experience, and CRM, simply to gain a coherent view of their business.</p>
          <p>The sector lacks the connective tissue that turns fragmented operational data into actionable strategic intelligence. There has been some AI adoption, but no solutions exist to make integrated data analysis easily accessible to everyone, allowing businesses to focus on what actually matters: optimisation.</p>
        </div>
      </div>

      {/* Full-width visual: chaos → lock chart sits on the page itself,
          centered, with no background container. */}
      <div className="problem__viz reveal">
        <div className="problem__viz-meta">
          <span className="problem__viz-meta-num">FIG · 02</span>
          <span>FRAGMENTED · UNIFIED</span>
        </div>
        <Systems />
      </div>
    </section>
  );
}

window.Problem = Problem;
