/* global React */
const { useState: useStateHiw, useEffect: useEffectHiw, useRef: useRefHiw } = React;

// Step-keyed conversation script. Each entry advances "activeStep".
const SCRIPT = [
  { step: 0, kind: 'system', text: '11:30 — continuous scan running' },
  { step: 0, kind: 'system', text: '18 arrivals checked vs Breezeway' },

  { step: 1, kind: 'you', text: 'Hey Maria — you’re assigned to 15 Pine Hollow today at 11am. Still on track? Let me know if anything’s changed.', time: '11:31' },
  { step: 1, kind: 'them', text: 'All set, heading over now 🧹', time: '11:32' },

  { step: 1, kind: 'you', text: 'Hey Diego — checking in on your 412 Ridgeway clean at 2pm. Everything good on your end?', time: '11:31' },
  { step: 1, kind: 'them', text: 'Confirmed, leaving in 20', time: '11:38' },

  { step: 1, kind: 'you', text: 'Hey Sam — you’re scheduled for 88 Larkspur Lane at 11am. Let me know you’re on track.', time: '11:31' },

  { step: 2, kind: 'warn', text: 'No reply to text or call from Sam · flagging as risk' },
  { step: 2, kind: 'system', text: 'coordinator notified · backup auto-contacted' },
  { step: 2, kind: 'you', text: 'Jenna — Sam isn’t reachable for 88 Larkspur at 11am. Any chance you can cover? I can send you the details now.', time: '12:02' },
  { step: 2, kind: 'them', text: 'Yes, picking up keys now', time: '12:04' },

  { step: 3, kind: 'system', text: 'same logic running · maintenance · inspections · guest issues' },
  { step: 3, kind: 'warn', text: '7 open loops · 7 closed by 12:18' },
];

function HowItWorks() {
  const steps = [
    'Every 30 minutes, the system checks every arrival scheduled for today against task completion status in your operations tool.',
    'For any arrival where a clean hasn’t been confirmed, it automatically reaches out to the assigned cleaner via SMS or WhatsApp — a natural, conversational message asking if they’re on track.',
    'No reply to text or call is treated as a risk signal. The system flags the arrival, notifies your coordinator, and optionally contacts the backup cleaner automatically.',
    'The same logic runs for maintenance vendors, inspection sign-offs, and unresolved guest issues. Every open loop gets closed or escalated. Nothing waits until 3pm.',
  ];

  const [idx, setIdx] = useStateHiw(-1);
  const [running, setRunning] = useStateHiw(false);
  const phoneRef = useRefHiw(null);
  const msgsRef = useRefHiw(null);

  // Auto-start when phone scrolls into view
  useEffectHiw(() => {
    const el = phoneRef.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !running) {
          setRunning(true);
        }
      });
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [running]);

  useEffectHiw(() => {
    if (!running) return;
    if (idx >= SCRIPT.length - 1) {
      // Loop
      const t = setTimeout(() => setIdx(-1), 5200);
      return () => clearTimeout(t);
    }
    const nextItem = SCRIPT[idx + 1];
    // Vary delays — longer pauses on user messages and system events
    const delay = idx === -1 ? 400 :
      nextItem.kind === 'you' ? 1200 :
      nextItem.kind === 'them' ? 1400 :
      nextItem.kind === 'warn' ? 1500 : 900;
    const t = setTimeout(() => setIdx((i) => i + 1), delay);
    return () => clearTimeout(t);
  }, [idx, running]);

  // Scroll messages container to bottom on new message
  useEffectHiw(() => {
    if (msgsRef.current) {
      msgsRef.current.scrollTop = msgsRef.current.scrollHeight;
    }
  }, [idx]);

  const activeStep = idx < 0 ? 0 : SCRIPT[idx].step;
  const visible = idx < 0 ? [] : SCRIPT.slice(0, idx + 1);

  return (
    <section id="how">
      <span className="section-mark">&sect; 03 / Mechanism</span>
      <div className="wrap">
        <div style={{ maxWidth: '52ch' }}>
          <Reveal><span className="eyebrow">How it actually works</span></Reveal>
          <Reveal delay={80}>
            <h2 className="h-section" style={{ marginTop: 22 }}>
              How it catches problems <em>early</em>
            </h2>
          </Reveal>
          <Reveal delay={140}>
            <p className="lead" style={{ marginTop: 22 }}>
              It doesn&apos;t just read your tools. It actively closes the loop with the people in the field.
            </p>
          </Reveal>
        </div>

        <div className="hiw">
          <Reveal>
            <div className="hiw-steps">
              {steps.map((s, i) => (
                <div key={i} className={`hiw-step ${i === activeStep && idx >= 0 ? 'active' : ''}`}>
                  <span className="hiw-step-num">0{i + 1}</span>
                  <p>{s}</p>
                </div>
              ))}
            </div>
          </Reveal>

          <Reveal delay={120}>
            <div className="phone" ref={phoneRef}>
              <div className="phone-screen">
                <div className="phone-header">
                  <div className="name">Ops Agent</div>
                  <div className="sub">&rarr; Cleaner channel &middot; live</div>
                </div>
                <div className="msgs" ref={msgsRef} style={{ maxHeight: 600, overflow: 'hidden' }}>
                  {visible.map((m, i) => {
                    if (m.kind === 'system') {
                      return <div key={i} className="msg system">{m.text}</div>;
                    }
                    if (m.kind === 'warn') {
                      return <div key={i} className="msg warn">&#9888; {m.text}</div>;
                    }
                    return (
                      <div key={i} className={`msg ${m.kind}`}>
                        {m.text}
                        {m.time && <span className="time">{m.time}</span>}
                      </div>
                    );
                  })}
                  {running && idx >= 0 && idx < SCRIPT.length - 1 && SCRIPT[idx + 1] && SCRIPT[idx + 1].kind === 'them' && (
                    <div className="typing"><span></span><span></span><span></span></div>
                  )}
                </div>
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

window.HowItWorks = HowItWorks;
