// Automation ROI section
// Replaces the former founding-schools block with the v1 automation math content,
// redesigned for the v2 light institutional system.

const ROI_PANELS = [
  {
    label: 'The old way',
    startValue: 0,
    endValue: 2200,
    unit: 'Hours wasted / year',
    detail: '12 mins roll call x 50 classrooms x 220 school days.',
    note: 'Valuable teaching time lost to administrative busywork.',
    color: 'var(--crimson)',
    startColor: '#1f6f52',
    endColor: '#b8314a',
    soft: 'rgba(184, 49, 74, 0.08)',
  },
  {
    label: 'The EduGuard way',
    startValue: 2200,
    endValue: 0,
    unit: 'Minutes wasted',
    detail: 'Attendance is instant, background, and fully autonomous.',
    note: 'Teachers focus on teaching.',
    color: 'var(--green)',
    startColor: '#b8314a',
    endColor: '#1f6f52',
    soft: 'rgba(31, 111, 82, 0.1)',
  },
];

function mixHexColor(from, to, progress) {
  const parse = (hex) => hex.replace('#', '').match(/.{1,2}/g).map((part) => parseInt(part, 16));
  const [fr, fg, fb] = parse(from);
  const [tr, tg, tb] = parse(to);
  const mix = (a, b) => Math.round(a + (b - a) * progress);
  return `rgb(${mix(fr, tr)}, ${mix(fg, tg)}, ${mix(fb, tb)})`;
}

function RoiCounter({ startValue, endValue, startColor, endColor, glowColor, duration = 2500 }) {
  const [value, setValue] = useState(startValue);
  const [currentColor, setCurrentColor] = useState(startColor);
  const [complete, setComplete] = useState(false);
  const ref = useRef(null);
  const started = useRef(false);

  useEffect(() => {
    const counter = ref.current;
    if (!counter) return undefined;

    const runCounter = () => {
      if (started.current) return;
      started.current = true;

      if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
        setValue(endValue);
        setCurrentColor(endColor);
        setComplete(true);
        return;
      }

      const animationStart = performance.now();
      const change = endValue - startValue;

      const step = (time) => {
        const progress = Math.min(1, (time - animationStart) / duration);
        const eased = 1 - Math.pow(1 - progress, 3);
        setValue(Math.round(startValue + change * eased));
        setCurrentColor(mixHexColor(startColor, endColor, eased));

        if (progress < 1) {
          requestAnimationFrame(step);
        } else {
          setValue(endValue);
          setCurrentColor(endColor);
          setComplete(true);
        }
      };

      requestAnimationFrame(step);
    };

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) runCounter();
      });
    }, { threshold: 0.42 });

    observer.observe(counter);
    return () => observer.disconnect();
  }, [startValue, endValue, startColor, endColor, duration]);

  return (
    <span
      ref={ref}
      className={`roi-counter-value${complete ? ' is-complete' : ''}`}
      style={{
        color: currentColor,
        '--roi-glow': glowColor,
      }}
    >
      {value.toLocaleString('en-IN')}
    </span>
  );
}

function AutomationMathSection() {
  return (
    <section id="roi" className="section" style={{
      background: 'var(--bg-1)',
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
      overflow: 'hidden',
    }}>
      <div className="dot-grid" style={{ opacity: 0.45, maskImage: 'linear-gradient(to bottom, transparent, black 18%, black 76%, transparent)' }} />
      <div className="wrap" style={{ position: 'relative' }}>
        <SectionHeader
          eyebrow="The ROI"
          title="The raw math of"
          italicTail="automation."
          subtitle="Schools run on tight schedules. See the impact of intelligent automation vs. legacy manual processes."
          align="center"
        />

        <div className="roi-shell card card-elevated" style={{
          padding: 0,
          overflow: 'hidden',
          background: 'linear-gradient(180deg, var(--bg-1) 0%, var(--bg-0) 100%)',
          borderColor: 'var(--line-strong)',
        }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'minmax(0, 1fr) auto minmax(0, 1fr)',
            alignItems: 'stretch',
          }} className="roi-compare-grid">
            {ROI_PANELS.map((panel, i) => (
              <React.Fragment key={panel.label}>
                <div className="roi-panel" style={{
                  padding: '48px 44px',
                  minHeight: 360,
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'space-between',
                  position: 'relative',
                }}>
                  <div>
                    <div style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: 8,
                      padding: '6px 11px',
                      borderRadius: 100,
                      border: '1px solid var(--line)',
                      background: panel.soft,
                      color: panel.color,
                      marginBottom: 30,
                    }}>
                      <span style={{
                        width: 7,
                        height: 7,
                        borderRadius: '50%',
                        background: panel.color,
                      }} />
                      <span className="mono" style={{
                        fontSize: 10.5,
                        letterSpacing: '0.15em',
                        textTransform: 'uppercase',
                        fontWeight: 700,
                      }}>{panel.label}</span>
                    </div>

                    <div className="display" style={{
                      fontSize: 'clamp(64px, 10vw, 118px)',
                      lineHeight: 0.9,
                      fontVariantNumeric: 'tabular-nums',
                    }}>
                      <RoiCounter
                        startValue={panel.startValue}
                        endValue={panel.endValue}
                        startColor={panel.startColor}
                        endColor={panel.endColor}
                        glowColor={panel.endColor}
                      />
                    </div>
                    <div style={{
                      marginTop: 14,
                      fontSize: 19,
                      fontWeight: 600,
                      color: 'var(--ink-0)',
                      letterSpacing: 0,
                    }}>
                      {panel.unit}
                    </div>
                  </div>

                  <div style={{
                    marginTop: 32,
                    paddingTop: 22,
                    borderTop: '1px solid var(--line)',
                  }}>
                    <p style={{ color: 'var(--ink-1)', fontSize: 15, lineHeight: 1.6, marginBottom: 8 }}>
                      {panel.detail}
                    </p>
                    <p style={{
                      color: i === 1 ? 'var(--green)' : 'var(--ink-2)',
                      fontSize: 14,
                      lineHeight: 1.55,
                      fontWeight: i === 1 ? 600 : 400,
                    }}>
                      {panel.note}
                    </p>
                  </div>
                </div>

                {i === 0 && (
                  <div className="roi-divider" style={{
                    width: 1,
                    background: 'var(--line)',
                    margin: '36px 0',
                    position: 'relative',
                  }}>
                    <div className="roi-vs" style={{
                      position: 'absolute',
                      top: '50%',
                      left: '50%',
                      transform: 'translate(-50%, -50%)',
                      width: 48,
                      height: 48,
                      borderRadius: '50%',
                      background: 'var(--ink-0)',
                      color: 'var(--bg-1)',
                      border: '4px solid var(--bg-1)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontFamily: 'var(--font-mono)',
                      fontSize: 10,
                      letterSpacing: '0.12em',
                      fontWeight: 700,
                    }}>
                      VS
                    </div>
                  </div>
                )}
              </React.Fragment>
            ))}
          </div>

          <div style={{
            borderTop: '1px solid var(--line)',
            padding: '26px 32px',
            background: 'var(--ink-0)',
            color: 'var(--bg-1)',
            display: 'grid',
            gridTemplateColumns: 'minmax(0, 1fr) auto',
            gap: 24,
            alignItems: 'center',
          }} className="roi-bottom">
            <div>
              <div className="mono" style={{
                fontSize: 10.5,
                letterSpacing: '0.15em',
                textTransform: 'uppercase',
                color: 'var(--brand-soft)',
                marginBottom: 8,
              }}>
                Annual recovery
              </div>
              <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: 0 }}>
                Give your teachers back <span style={{ color: 'var(--brand-soft)' }}>2,200 hours</span> a year.
              </div>
            </div>
            <div className="roi-formula" style={{
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              flexWrap: 'wrap',
              justifyContent: 'flex-end',
              fontFamily: 'var(--font-mono)',
              fontSize: 11,
              color: 'rgba(255,255,255,0.76)',
            }}>
              {['12 min', '50 rooms', '220 days'].map((item, i) => (
                <React.Fragment key={item}>
                  <span style={{
                    padding: '7px 10px',
                    borderRadius: 8,
                    background: 'rgba(255,255,255,0.08)',
                    border: '1px solid rgba(255,255,255,0.12)',
                    whiteSpace: 'nowrap',
                  }}>{item}</span>
                  {i < 2 && <span style={{ color: 'rgba(255,255,255,0.38)' }}>x</span>}
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .roi-counter-value {
          display: inline-block;
          min-width: 2.55em;
          transition: color 0.3s ease;
        }
        @media (max-width: 900px) {
          .roi-compare-grid { grid-template-columns: 1fr !important; }
          .roi-divider { width: auto !important; height: 1px !important; margin: 0 28px !important; }
          .roi-vs { top: 50% !important; left: 50% !important; }
          .roi-panel { min-height: auto !important; padding: 38px 28px !important; }
          .roi-bottom { grid-template-columns: 1fr !important; }
          .roi-formula { justify-content: flex-start !important; }
        }
        @media (max-width: 560px) {
          .roi-panel { padding: 32px 22px !important; }
          .roi-bottom { padding: 24px 22px !important; }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { AutomationMathSection });
