/* ═══════════════════════════════════════════════════════
   IKIGAI · Living Orb · Multi-state Cosmic Entity
   ═══════════════════════════════════════════════════════ */

const { useEffect, useRef, useState } = React;

// ───────────── Orb State Context ─────────────
const OrbContext = React.createContext({ state: 'awake', setState: () => {} });

function OrbProvider({ children }) {
  const [state, setState] = useState('awake');
  const [accent, setAccent] = useState(null); // override color
  return (
    <OrbContext.Provider value={{ state, setState, accent, setAccent }}>
      {children}
    </OrbContext.Provider>
  );
}

// State → color mapping
const ORB_STATES = {
  awake:        { core: '#7EF6E2', ring: '#6EA8FF', halo: '#9B8CFF' },
  scattered:    { core: '#9B8CFF', ring: '#C8D4F0', halo: '#6EA8FF' },
  aligning:     { core: '#7EF6E2', ring: '#F5DFA7', halo: '#6EA8FF' },
  pages:        { core: '#6EA8FF', ring: '#7EF6E2', halo: '#9B8CFF' },
  memory:       { core: '#7EF6E2', ring: '#6EA8FF', halo: '#C8D4F0' },
  neural:       { core: '#9B8CFF', ring: '#7EF6E2', halo: '#6EA8FF' },
  architecture: { core: '#6EA8FF', ring: '#9B8CFF', halo: '#7EF6E2' },
  shield:       { core: '#F5DFA7', ring: '#7EF6E2', halo: '#6EA8FF' },
  rings:        { core: '#C8D4F0', ring: '#6EA8FF', halo: '#9B8CFF' },
  listening:    { core: '#7EF6E2', ring: '#6EA8FF', halo: '#9B8CFF' },
  thinking:     { core: '#9B8CFF', ring: '#7EF6E2', halo: '#6EA8FF' },
  searching:    { core: '#6EA8FF', ring: '#7EF6E2', halo: '#9B8CFF' },
  responding:   { core: '#7EF6E2', ring: '#F5DFA7', halo: '#6EA8FF' },
  pulse:        { core: '#9B8CFF', ring: '#7EF6E2', halo: '#F5DFA7' },
  stable:       { core: '#FFFFFF', ring: '#C8D4F0', halo: '#7EF6E2' },
};

// ───────────── Living Orb ─────────────
function LivingOrb({ size = 360, follow = true, className = '', style = {} }) {
  const { state, accent } = React.useContext(OrbContext);
  const ref = useRef(null);
  const offset = useRef({ x: 0, y: 0, tx: 0, ty: 0 });
  const colors = accent || ORB_STATES[state] || ORB_STATES.awake;

  // Cursor follow with lerp
  useEffect(() => {
    if (!follow) return;
    let raf;
    function onMove(e) {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = (e.clientX - cx);
      const dy = (e.clientY - cy);
      const dist = Math.sqrt(dx * dx + dy * dy);
      const maxR = 400;
      if (dist < maxR) {
        const k = (1 - dist / maxR) * 0.06;
        offset.current.tx = dx * k;
        offset.current.ty = dy * k;
      } else {
        offset.current.tx *= 0.92;
        offset.current.ty *= 0.92;
      }
    }
    function tick() {
      offset.current.x += (offset.current.tx - offset.current.x) * 0.08;
      offset.current.y += (offset.current.ty - offset.current.y) * 0.08;
      if (ref.current) {
        ref.current.style.setProperty('--ox', offset.current.x.toFixed(2) + 'px');
        ref.current.style.setProperty('--oy', offset.current.y.toFixed(2) + 'px');
        // broadcast position to constellation
        const r = ref.current.getBoundingClientRect();
        window.dispatchEvent(new CustomEvent('ikigai:orb', {
          detail: { x: r.left + r.width / 2, y: r.top + r.height / 2 }
        }));
      }
      raf = requestAnimationFrame(tick);
    }
    window.addEventListener('mousemove', onMove, { passive: true });
    raf = requestAnimationFrame(tick);
    return () => {
      window.removeEventListener('mousemove', onMove);
      cancelAnimationFrame(raf);
    };
  }, [follow]);

  return (
    <div
      ref={ref}
      className={`living-orb living-orb--${state} ${className}`}
      style={{
        '--orb-size': size + 'px',
        '--orb-core': colors.core,
        '--orb-ring': colors.ring,
        '--orb-halo': colors.halo,
        ...style,
      }}
      aria-hidden="true"
    >
      {/* outer corona */}
      <div className="orb-corona" />
      {/* atmospheric ring */}
      <div className="orb-atmosphere" />
      {/* orbital rings */}
      <div className="orb-ring orb-ring--1">
        <span className="orb-ring__dot" />
      </div>
      <div className="orb-ring orb-ring--2">
        <span className="orb-ring__dot" />
      </div>
      <div className="orb-ring orb-ring--3" />
      {/* core */}
      <div className="orb-core">
        <div className="orb-core__glow" />
        <div className="orb-core__inner" />
        <div className="orb-core__highlight" />
      </div>
      {/* state-specific accessories */}
      <StateAccessories state={state} />
    </div>
  );
}

// ───────────── State-specific overlay elements ─────────────
function StateAccessories({ state }) {
  if (state === 'scattered') {
    return (
      <div className="orb-fragments">
        {[...Array(8)].map((_, i) => (
          <span key={i} className="orb-fragment" style={{ '--i': i }} />
        ))}
      </div>
    );
  }
  if (state === 'neural') {
    return (
      <svg className="orb-neural" viewBox="-100 -100 200 200" aria-hidden="true">
        {[...Array(7)].map((_, i) => {
          const a = (i / 7) * Math.PI * 2;
          const x = Math.cos(a) * 78;
          const y = Math.sin(a) * 78;
          return (
            <g key={i}>
              <line x1="0" y1="0" x2={x} y2={y}
                    stroke="rgba(155,140,255,0.32)" strokeWidth="0.6" />
              <circle cx={x} cy={y} r="3" fill="rgba(126,246,226,0.9)" />
            </g>
          );
        })}
      </svg>
    );
  }
  if (state === 'shield') {
    return (
      <div className="orb-shield">
        <div className="orb-shield__layer" style={{ animationDelay: '0s' }} />
        <div className="orb-shield__layer" style={{ animationDelay: '1s' }} />
        <div className="orb-shield__layer" style={{ animationDelay: '2s' }} />
      </div>
    );
  }
  if (state === 'rings') {
    return (
      <div className="orb-access-rings">
        {[0.5, 0.7, 0.9, 1.1].map((s, i) => (
          <div key={i} className="orb-access-ring" style={{ '--s': s, '--d': i * 0.5 + 's' }} />
        ))}
      </div>
    );
  }
  if (state === 'pages') {
    return (
      <div className="orb-pages">
        {[0, 1, 2].map(i => (
          <span key={i} className="orb-page" style={{ '--i': i }} />
        ))}
      </div>
    );
  }
  if (state === 'memory') {
    return (
      <div className="orb-layers">
        {[0, 1, 2, 3].map(i => (
          <span key={i} className="orb-layer" style={{ '--i': i }} />
        ))}
      </div>
    );
  }
  if (state === 'architecture') {
    return (
      <div className="orb-grid">
        {[...Array(5)].map((_, i) => (
          <span key={i} className="orb-grid__line" style={{ '--i': i }} />
        ))}
      </div>
    );
  }
  if (state === 'searching' || state === 'thinking' || state === 'listening' || state === 'responding') {
    return (
      <div className="orb-pulse-rings">
        <span className="orb-pulse-ring" style={{ animationDelay: '0s' }} />
        <span className="orb-pulse-ring" style={{ animationDelay: '0.6s' }} />
        <span className="orb-pulse-ring" style={{ animationDelay: '1.2s' }} />
      </div>
    );
  }
  return null;
}

window.LivingOrb = LivingOrb;
window.OrbProvider = OrbProvider;
window.OrbContext = OrbContext;
window.ORB_STATES = ORB_STATES;
