/* global React */
const { useState: useS, useEffect: useE, useRef: useR } = React;

/* hook: run a looping "play" counter while element is on screen */
function usePlay(period = 4800) {
  const ref = useR(null);
  const [play, setPlay] = useS(0);
  const [vis, setVis] = useS(false);
  useE(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => setVis(e.isIntersecting), { threshold: 0.4 });
    io.observe(el); return () => io.disconnect();
  }, []);
  useE(() => {
    if (!vis) return;
    setPlay((p) => p + 1);
    const id = setInterval(() => setPlay((p) => p + 1), period);
    return () => clearInterval(id);
  }, [vis, period]);
  return [ref, play];
}

/* ============ Feature 1 — transcript → insights ============ */
function AutoInsights() {
  const [ref, play] = usePlay(5200);
  const insights = [
    ['var(--green-500)', 'Confidence milestone', 'Devon led the client retro solo for the first time.'],
    ['var(--clay)', 'Watch-out', 'Still hesitant giving upward feedback to senior peers.'],
    ['var(--green-700)', 'Suggested action', 'Shadow Maya in Thursday\u2019s stakeholder review.'],
  ];
  return (
    <div ref={ref} className="mck" style={{ width: '100%', maxWidth: 440, padding: 20 }} key={play}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
        <span style={{ display: 'inline-flex', gap: 3, alignItems: 'flex-end', height: 18 }}>
          {[8, 14, 6, 17, 10, 13, 7].map((h, i) => (
            <span key={i} style={{ width: 3, borderRadius: 2, background: 'var(--green-500)', height: h,
              animation: `eq .9s ease-in-out ${i * 0.08}s infinite alternate` }} />
          ))}
        </span>
        <span style={{ fontSize: 13, fontWeight: 600 }}>Session 4 transcript</span>
        <span className="mck-chip" style={{ marginLeft: 'auto' }}>38:12</span>
      </div>
      {/* transcript fading lines */}
      <div style={{ display: 'grid', gap: 7, paddingBottom: 14, marginBottom: 14, borderBottom: '1px dashed var(--line)' }}>
        {[88, 70, 94, 60].map((w, i) => (
          <div key={i} style={{ height: 7, width: w + '%', borderRadius: 4, background: 'var(--paper-2)',
            opacity: 0, animation: `fadeline .5s ease ${0.2 + i * 0.18}s forwards` }} />
        ))}
      </div>
      <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--green-600)', letterSpacing: '.06em',
        textTransform: 'uppercase', marginBottom: 12, opacity: 0, animation: 'fadeline .5s ease 1.1s forwards' }}>
        ✦ Auto-digested into insights
      </div>
      {insights.map(([c, t, d], i) => (
        <div key={i} style={{ display: 'flex', gap: 11, padding: '10px 0', borderTop: i ? '1px solid var(--line-soft)' : 'none',
          opacity: 0, transform: 'translateY(8px)', animation: `pop .5s cubic-bezier(.16,.84,.36,1) ${1.4 + i * 0.45}s forwards` }}>
          <span style={{ width: 8, height: 8, borderRadius: 3, background: c, marginTop: 5, flex: 'none' }} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{t}</div>
            <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.45, marginTop: 1 }}>{d}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ============ Feature 3 — calendar auto-booking ============ */
function CalendarSync() {
  const [ref, play] = usePlay(5000);
  const slots = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  // matched day index
  const match = 3;
  return (
    <div ref={ref} className="mck" style={{ width: '100%', maxWidth: 440, padding: 22 }} key={play}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 18 }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>Finding a time that works</span>
        <span className="mck-chip" style={{ marginLeft: 'auto' }}>2 calendars synced</span>
      </div>
      {[['Maya', 'Mentor', 'var(--green-600)'], ['Devon', 'Mentee', 'var(--clay)']].map(([name, role, col], r) => (
        <div key={name} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
          <div style={{ width: 64, flex: 'none' }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{name}</div>
            <div style={{ fontSize: 11, color: 'var(--muted)' }}>{role}</div>
          </div>
          <div style={{ display: 'flex', gap: 6, flex: 1 }}>
            {slots.map((s, i) => {
              const free = (r === 0 ? [1, 3, 4] : [0, 3]).includes(i);
              const isMatch = i === match;
              return (
                <div key={s} style={{ flex: 1, textAlign: 'center' }}>
                  <div style={{ fontSize: 9.5, color: 'var(--faint)', marginBottom: 4 }}>{s}</div>
                  <div style={{ height: 30, borderRadius: 7, border: '1px solid',
                    borderColor: isMatch ? 'var(--green-500)' : (free ? 'var(--sage-200)' : 'var(--line-soft)'),
                    background: free ? 'var(--sage-100)' : 'var(--paper-2)',
                    boxShadow: isMatch ? '0 0 0 3px rgba(69,195,134,.28)' : 'none',
                    opacity: 0, animation: `pop .4s ease ${0.2 + i * 0.08 + r * 0.3}s forwards`,
                    ...(isMatch ? { animation: `pop .4s ease ${0.2 + i * 0.08 + r * 0.3}s forwards, matchpulse 1.2s ease 1.6s` } : {}) }} />
                </div>
              );
            })}
          </div>
        </div>
      ))}
      {/* booked confirmation */}
      <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px',
        background: 'var(--green-900)', borderRadius: 13, color: '#fff',
        opacity: 0, transform: 'translateY(10px)', animation: 'pop .55s cubic-bezier(.16,.84,.36,1) 2.4s forwards' }}>
        <div style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(255,255,255,.14)', display: 'grid', placeItems: 'center', flex: 'none' }}>
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none"><path d="M5 12.5l4 4 10-10" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>Session 5 booked · Thu 14:00</div>
          <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.7)' }}>Added to both calendars · invites sent</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AutoInsights, CalendarSync });
