/* ==========================================================================
   Process.jsx | 09 How it works
   Six-step timeline. As you scroll, a line fills down the steps, a broom
   rides its tip and each step lights up when it reaches the reading line.
   ========================================================================== */

const MC_STEPS = [
  { title: 'Get in touch', text: 'Tell us about your space and the cleaning service you need.' },
  { title: 'Choose your service', text: 'Select house cleaning, housekeeping, end-of-lease or office cleaning.' },
  { title: 'Share the details', text: 'Provide your property details, cleaning requirements and preferred schedule.' },
  { title: 'Receive your quote', text: 'Get a quote based on the information you’ve provided.' },
  { title: 'Book your clean', text: 'Confirm the service and arrange a time that suits you.' },
  { title: 'Enjoy your fresh space', text: 'Leave the cleaning to us and enjoy the result.' },
];

function MCProcess({ onIntent }) {
  const stepsRef = React.useRef(null);
  const [procTrack, setProcTrack] = React.useState({ top: 0, height: 0, fill: 0 });
  const [procActive, setProcActive] = React.useState(-1);

  React.useEffect(() => {
    let frame = 0;
    const measure = () => {
      frame = 0;
      const list = stepsRef.current;
      if (!list) return;
      const nodes = list.querySelectorAll('.mc-step__node');
      if (!nodes.length) return;
      const listRect = list.getBoundingClientRect();
      const firstRect = nodes[0].getBoundingClientRect();
      const lastRect = nodes[nodes.length - 1].getBoundingClientRect();
      const start = firstRect.top + firstRect.height / 2 - listRect.top;
      const end = lastRect.top + lastRect.height / 2 - listRect.top;
      const readingLine = window.innerHeight * 0.62;
      const fill = Math.min(Math.max(readingLine - (listRect.top + start), 0), end - start);
      let active = -1;
      nodes.forEach((node, index) => {
        const rect = node.getBoundingClientRect();
        if (rect.top + rect.height / 2 <= readingLine + 1) active = index;
      });
      setProcTrack({ top: start, height: end - start, fill });
      setProcActive(active);
    };
    const schedule = () => {
      if (!frame) frame = window.requestAnimationFrame(measure);
    };
    measure();
    window.addEventListener('scroll', schedule, { passive: true });
    window.addEventListener('resize', schedule);
    return () => {
      window.removeEventListener('scroll', schedule);
      window.removeEventListener('resize', schedule);
      if (frame) window.cancelAnimationFrame(frame);
    };
  }, []);

  const handleQuote = (event) => {
    event.preventDefault();
    onIntent('quote');
  };

  return (
    <section className="mc-section mc-process" id="how-it-works" aria-labelledby="mc-process-title">
      <div className="mc-wrap mc-process__grid">
        <div className="mc-process__aside">
          <header className="mc-head" data-reveal>
            <MCEyebrow>Simple as dusting</MCEyebrow>
            <h2 className="mc-h2" id="mc-process-title">
              Getting a cleaner space is easier than you think.
            </h2>
            <p className="mc-lede">Six simple steps, from your first message to a fresh space.</p>
          </header>
          <a href="#quote" className="mc-btn" onClick={handleQuote}>
            Get a free quote
            <MCIcon name="sparkle" className="mc-btn__spark" />
          </a>
          <div className="mc-process__note">
            <MCDusty decorative />
            <p>Dusty’s favourite step? Number six.</p>
          </div>
        </div>

        <ol className="mc-steps" ref={stepsRef}>
          <span className="mc-steps__track" aria-hidden="true" style={{ top: procTrack.top, height: procTrack.height }} />
          <span className="mc-steps__fill" aria-hidden="true" style={{ top: procTrack.top, height: procTrack.fill }} />
          <span className="mc-steps__broom" aria-hidden="true" style={{ top: procTrack.top + procTrack.fill }}>
            <MCIcon name="broom" />
          </span>
          {MC_STEPS.map((step, index) => {
            const state = index === procActive ? 'is-active' : index < procActive ? 'is-done' : '';
            const isLast = index === MC_STEPS.length - 1;
            return (
              <li key={step.title} className={`mc-step ${state}`}>
                <span className="mc-step__node" aria-hidden="true">
                  {isLast && index <= procActive ? <MCIcon name="sparkle" /> : index + 1}
                </span>
                <div className="mc-step__body">
                  <h3 className="mc-step__title">
                    <span className="mc-sr">Step {index + 1}: </span>
                    {step.title}
                  </h3>
                  <p className="mc-step__text">{step.text}</p>
                </div>
              </li>
            );
          })}
        </ol>
      </div>
    </section>
  );
}

Object.assign(window, { MCProcess });
