/* global React, window */
const { useState: useStateTR, useEffect: useEffectTR, useRef: useRefTR } = React;
const { PHASES, ENGINES: ENG_TR_DEFAULT, fmt: fmtTR, calc: calcTR } = window;

function Trajectory({ engines }) {
  const [active, setActive] = useStateTR(0);
  const containerRef = useRefTR(null);
  const phaseRefs = useRefTR([]);

  // If caller passes live engines (from scenario builder), use those.
  // Otherwise fall back to module defaults so the component still renders standalone.
  const sourceEngines = engines || ENG_TR_DEFAULT;

  useEffectTR(() => {
    const onScroll = () => {
      if (!containerRef.current) return;
      const viewportMid = window.innerHeight * 0.4;
      let best = 0, bestDist = Infinity;
      phaseRefs.current.forEach((el, i) => {
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const mid = rect.top + rect.height / 2;
        const dist = Math.abs(mid - viewportMid);
        if (dist < bestDist) { bestDist = dist; best = i; }
      });
      setActive(best);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Implied price for a phase uses the caller's live engine tunings (price, royalty,
  // margin, yield) applied to the phase's share matrix. If the user toggled an engine
  // off in the Scenario Builder, it contributes zero here too.
  const priceFor = (phase) => {
    let profit = 0;
    Object.entries(sourceEngines).forEach(([k, base]) => {
      if (!(k in phase.sm)) return;
      if (!base.enabled) return;
      const e = { ...base, enabled: true, share: phase.sm[k] };
      const r = calcTR(e);
      profit += r.profit;
    });
    return (profit * phase.pe) / (phase.sh * 1e6);
  };

  return (
    <div ref={containerRef} className="traj-stage">
      <div className="traj-rail">
        <div className="card-label" style={{ marginBottom: 12 }}>Valuation Trajectory</div>
        {PHASES.map((p, i) => (
          <div
            key={i}
            className={`traj-phase ${active === i ? 'active' : ''}`}
            onClick={() => {
              phaseRefs.current[i]?.scrollIntoView({ block: 'start', behavior: 'smooth' });
            }}
          >
            <div className="traj-phase-label">{p.years}</div>
            <div className="traj-phase-name">{p.name}</div>
            <div className="traj-phase-price">${priceFor(p).toFixed(0)}</div>
          </div>
        ))}
      </div>

      <div>
        {PHASES.map((p, i) => {
          const price = priceFor(p);
          return (
            <div
              key={i}
              ref={(el) => (phaseRefs.current[i] = el)}
              style={{
                minHeight: '70vh',
                padding: '48px 0',
                borderBottom: i < PHASES.length - 1 ? '1px solid var(--line)' : 'none',
                opacity: active === i ? 1 : 0.55,
                transition: 'opacity 0.35s',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 16, marginBottom: 8 }}>
                <div className="num" style={{ fontSize: 12, color: 'var(--accent)', letterSpacing: '0.12em' }}>{p.years.toUpperCase()}</div>
                {p.current && <span className="chip accent">You are here</span>}
              </div>
              <h2 className="serif" style={{ fontSize: 40, lineHeight: 1.05, letterSpacing: '-0.02em', color: 'var(--fg-0)', marginBottom: 24 }}>
                Phase {i + 1} — {p.name}
              </h2>

              <div className="traj-metrics" style={{ marginBottom: 24 }}>
                <div className="minibox">
                  <div className="card-label">Implied share price</div>
                  <div className="num" style={{ fontSize: 28, color: 'var(--accent)', marginTop: 4 }}>${price.toFixed(0)}</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 4 }}>P/E {p.pe} · {p.sh}M sh</div>
                </div>
                <div className="minibox">
                  <div className="card-label">Revenue</div>
                  <div className="num" style={{ fontSize: 20, color: 'var(--fg-0)', marginTop: 4 }}>{p.rev}</div>
                </div>
                <div className="minibox">
                  <div className="card-label">Plants deployed</div>
                  <div className="num" style={{ fontSize: 20, color: 'var(--fg-0)', marginTop: 4 }}>{p.plants}</div>
                </div>
                <div className="minibox">
                  <div className="card-label">Market state</div>
                  <div style={{ fontSize: 13, color: 'var(--fg-1)', marginTop: 4, lineHeight: 1.4 }}>
                    {i === 0 && 'De-risking'}
                    {i === 1 && 'Early commercial'}
                    {i === 2 && 'Scaling'}
                    {i === 3 && 'Standard'}
                  </div>
                </div>
              </div>

              <div className="traj-2col">
                <div>
                  <div className="card-label" style={{ marginBottom: 8 }}>Drivers</div>
                  <p style={{ fontSize: 13.5, color: 'var(--fg-1)', lineHeight: 1.65, marginBottom: 16 }}>{p.drivers}</p>
                  <div className="card-label" style={{ marginBottom: 8 }}>Catalysts</div>
                  <p style={{ fontSize: 13.5, color: 'var(--fg-1)', lineHeight: 1.65 }}>{p.catalysts}</p>
                </div>
                <div>
                  <div className="card-label" style={{ marginBottom: 8 }}>Historical precedent</div>
                  <p style={{ fontSize: 13.5, color: 'var(--fg-1)', lineHeight: 1.65, marginBottom: 16 }}>{p.precedent}</p>
                  <div className="card-label" style={{ marginBottom: 8 }}>Primary risk</div>
                  <p style={{ fontSize: 13.5, color: 'var(--neg)', lineHeight: 1.65 }}>{p.risk}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.Trajectory = Trajectory;
