// nyc-welcome-v2.jsx — v2 scrollytelling intro
//
// Sequence:
//   0  Question:   "Did you pay New York City taxes?"  [YES] [NO]
//   1  Reveal:     You've signed up for: NEW YORK CITY!
//   2  Thank you (rotating languages)
//   3  Membership perks overview
//   4  Spread across city departments
//   5  $40B stat
//   6  Bridge: "a few specials to start"  →  catalog

const THANK_YOUS = [
  { word: 'Thank you!',   lang: 'English',        dir: 'ltr' },
  { word: 'Dziękujemy!',  lang: 'Polish',          dir: 'ltr' },
  { word: '¡Gracias!',    lang: 'Spanish',         dir: 'ltr' },
  { word: '谢谢！',         lang: 'Chinese',         dir: 'ltr' },
  { word: 'Спасибо!',     lang: 'Russian',         dir: 'ltr' },
  { word: 'Mèsi!',        lang: 'Haitian Creole',  dir: 'ltr' },
  { word: '!شكراً',        lang: 'Arabic',          dir: 'rtl' },
  { word: 'Grazie!',      lang: 'Italian',         dir: 'ltr' },
  { word: 'ধন্যবাদ!',      lang: 'Bengali',         dir: 'ltr' },
  { word: 'Mahalo!',      lang: 'Hawaiian',        dir: 'ltr' },
];

function WelcomeBridgeCard({ perk, onEnter, onAdd, inPerks }) {
  const { photo, hasPhoto } = window.usePerkPhoto(perk.id, perk.photo_hint);

  return (
    <article className="wv2-bridge-card">
      {hasPhoto && (
        <div className="wv2-bridge-hero" onClick={onEnter}>
          <window.PerkImage photo={photo} photoHint={perk.photo_hint} variant="card" />
        </div>
      )}
      <div className="wv2-bridge-body" onClick={onEnter}>
        <div className="wv2-bridge-cat">{perk.cat}</div>
        <div className="wv2-bridge-name">{perk.name}</div>
        <div className="wv2-bridge-blurb">{perk.desc}</div>
      </div>
      {onAdd && (
        <div
          className="wv2-bridge-save"
          onClick={(e) => { e.stopPropagation(); onAdd(perk); }}
        >
          {inPerks ? '✓ saved' : '+ save'}
        </div>
      )}
    </article>
  );
}

function WelcomeV2({ onEnter, perksSet, onAdd }) {
  const [answered, setAnswered]   = React.useState(false);
  const [dismissing, setDismissing] = React.useState(false);
  const [noClicked, setNoClicked] = React.useState(false);
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [tyIdx, setTyIdx]         = React.useState(0);
  const [tyVisible, setTyVisible] = React.useState(true);

  // Lock scroll while the question is shown
  React.useEffect(() => {
    if (answered) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [answered]);

  // IntersectionObserver: animate sections + track active for progress dots
  React.useEffect(() => {
    if (!answered) return;
    const sections = Array.from(document.querySelectorAll('.wv2-section'));
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('visible');
            const i = sections.indexOf(e.target);
            if (i >= 0) setActiveIdx(i);
          }
        });
      },
      { threshold: 0.45 }
    );
    sections.forEach((s) => io.observe(s));
    return () => io.disconnect();
  }, [answered]);

  // Rotate thank-you language every ~2 seconds with a brief fade
  React.useEffect(() => {
    if (!answered) return;
    const tick = setInterval(() => {
      setTyVisible(false);
      setTimeout(() => {
        setTyIdx(i => (i + 1) % THANK_YOUS.length);
        setTyVisible(true);
      }, 300);
    }, 2200);
    return () => clearInterval(tick);
  }, [answered]);

  const onYes = () => {
    setDismissing(true);
    setTimeout(() => {
      setAnswered(true);
      window.scrollTo({ top: 0, behavior: 'auto' });
    }, 400);
  };

  const onNo = () => {
    if (noClicked) { onYes(); return; }
    setNoClicked(true);
  };

  const backToQuestion = () => {
    setAnswered(false);
    setDismissing(false);
    setNoClicked(false);
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  const totalScenes = 6;
  const current = THANK_YOUS[tyIdx];

  return (
    <div className="wv2-shell">
      <button className="wv2-skip" onClick={onEnter}>skip intro →</button>
      {answered && (
        <button type="button" className="wv2-back" onClick={backToQuestion}>
          ← Back
        </button>
      )}

      {/* progress dots — only meaningful once scrolling */}
      {answered && (
        <div className="wv2-progress" aria-hidden="true">
          {Array.from({ length: totalScenes }).map((_, i) => (
            <span key={i} className={i <= activeIdx ? 'on' : ''}></span>
          ))}
        </div>
      )}

      {/* ============ QUESTION ============ */}
      {!answered && (
        <div className={`wv2-question ${dismissing ? 'dismiss' : ''}`}>
          <div className="wv2-q-inner">
            <div className="wv2-q-rule">a single question</div>
            <h1 className="wv2-q">
              Did you pay<br />
              New York City<br />
              <span className="ink-tomato">taxes</span>?
            </h1>

            <div className="wv2-q-buttons">
              <button className="wv2-yn yes" onClick={onYes}>YES</button>
              <button className="wv2-yn no"  onClick={onNo}>NO</button>
            </div>

            {noClicked && (
              <div className="wv2-noresp">
                <p>Wanna see what New Yorkers get anyway?</p>
                <button className="wv2-yn yes wv2-yn-sm" onClick={onYes}>continue →</button>
              </div>
            )}

            <div className="wv2-q-foot">
              <span>NYC Perks&trade;</span>
              <span>Dutiful since 1898</span>
            </div>
          </div>
        </div>
      )}

      {/* ============ SCROLLYTELLER ============ */}
      {answered && (
        <main className="wv2-scroll">

          {/* Scene 1 — REVEAL */}
          <section className="wv2-section">
            {/* <button type="button" className="wv2-section-back" onClick={backToQuestion}>
              ← back to question
            </button> */}
            <div className="wv2-chapter">01 · you&rsquo;re in</div>
            <h1 className="wv2-bien-1">You&rsquo;ve signed up for:</h1>
            <h1 className="wv2-bien-2">New York City!</h1>
            <p className="wv2-bien-3">Your taxes cover more than you think.</p>
            <div className="wv2-hint">
              <span>scroll to continue</span>
              <span className="wv2-arrow">↓</span>
            </div>
          </section>

          {/* Scene 2 — THANK YOU */}
          <section className="wv2-section">
            <div className="wv2-chapter">02</div>
            <p className="wv2-prose">
              We know some of you have a choice when it comes to
              where to live. We just want to say &mdash;
            </p>
            <p
              className="wv2-script"
              dir={current.dir}
              style={{ opacity: tyVisible ? 1 : 0, transition: 'opacity 0.3s ease' }}
            >
              {current.word}
            </p>
          </section>

          {/* Scene 3 — MEMBERSHIP */}
          <section className="wv2-section">
            <div className="wv2-chapter">03 · what&rsquo;s included</div>
            <p className="wv2-prose">
              Included in your NYC membership are <em>hundreds</em> of perks across all five boroughs &mdash;
              services your tax dollars have already funded.
            </p>
            {/* <div className="wv2-boroughs">
              <span>Manhattan</span>
              <span>Brooklyn</span>
              <span>Queens</span>
              <span>The Bronx</span>
              <span>Staten Island</span>
            </div> */}
          </section>

          {/* Scene 4 — DEPARTMENTS (live vs coming) */}
          <section className="wv2-section">
            <div className="wv2-chapter">04 · dozens of departments; thousands of perks.</div>
            <p className="wv2-prose">
              The current catalog of perks includes{' '}
              <span className="ink-tomato">libraries, parks, social services, the department of education, and human resources administration</span>.
            </p>

            <div className="wv2-cats-wrap">
              <div className="wv2-cats">
                {/* Live now */}
                <span className="cat-live">NYPL</span>
                <span className="cat-live">DOE</span>
                <span className="cat-live">DPR</span>
                <span className="cat-live">HRA</span>
                {/* Coming soon */}
                <span className="cat-soon">DOHMH</span>
                <span className="cat-soon">MTA</span>
                <span className="cat-soon">H+H</span>
                <span className="cat-soon">OTI</span>
                <span className="cat-more">+ 30 agencies</span>
              </div>
              <div className="wv2-cats-legend">
                <span>&#9679; live now</span>
                <span>&#9675; coming soon</span>
              </div>
            </div>

            <p className="wv2-prose">
              <em>With more to come!</em>
            </p>
          </section>

          {/* Scene 5 — $40B */}
          <section className="wv2-section">
            <div className="wv2-chapter">05 · the gap</div>
            <div className="wv2-stat-num">$40B<sup>+</sup></div>
            <p className="wv2-prose">
              Despite taxes exceeding <strong>$40B</strong>, residents don&rsquo;t use
              many of the services available to them.
            </p>
            <p className="wv2-prose-sm">
              To make it easier to find and access what&rsquo;s included in their membership,
              we built this site. Enjoy.
            </p>
          </section>

          {/* Scene 6 — BRIDGE to catalog */}
          <section className="wv2-section wv2-bridge">
            <div className="wv2-chapter">06 · the menu</div>
            <h2 className="wv2-bridge-h">A few specials to start.</h2>
            <p className="wv2-prose-sm">Open the full catalog to browse all {window.PERKS ? window.PERKS.length : ''} perks.</p>

            <div className="wv2-bridge-grid">
              {((() => {
                // Show one curated perk per category as a diverse starting sample
                const ids = ['summerstage-city-parks-foundation', 'libby-by-overdrive', 'linkedin-learning', 'culture-pass'];
                const pinned = ids.map(id => window.PERKS.find(p => p.id === id)).filter(Boolean);
                return pinned.length === 4 ? pinned : window.PERKS.slice(0, 4);
              })()).map((p) => (
                <WelcomeBridgeCard
                  key={p.id}
                  perk={p}
                  onEnter={onEnter}
                  onAdd={onAdd}
                  inPerks={perksSet && perksSet.has(p.id)}
                />
              ))}
            </div>

            <button className="wv2-cta" onClick={onEnter}>Open the full catalog →</button>
          </section>

        </main>
      )}
    </div>
  );
}

window.WelcomeV2 = WelcomeV2;
