/* ProcessSection — tabbed video gallery for the PROCESS nav anchor. */
const { useState: useStateProc, useRef: useRefProc, useEffect: useEffectProc } = React;

const PROCESS_CATEGORIES = [
  {
    id: 'start',
    label: 'Start Here',
    blurb: 'How it works, who we are, and how we differ from iBuyers and realtors.',
    videos: [
      { title: 'Process Overview', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Process%20Overview.mp4' },
      { title: 'Selling Process Overview', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Selling%20Process%20Overview.mp4' },
      { title: 'How to Start the Process', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/How%20to%20Start%20Process.mp4' },
      { title: 'What is a Real Estate Investor?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/What%20is%20a%20Real%20Estate%20Investor.mp4' },
      { title: 'Realtor vs. Investor', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Realtor%20vs%20Investor.mp4' },
      { title: 'How We Differ from iBuyers', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/How%20We%20Differ%20from%20iBuyers.mp4' },
    ],
  },
  {
    id: 'offer',
    label: 'The Offer',
    blurb: 'How we determine value, structure offers, and handle negotiations.',
    videos: [
      { title: 'What is a Cash Offer?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/What%20is%20a%20Cash%20Offer%202.33.mp4' },
      { title: 'Negotiate Cash Offers', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Negotiate%20Cash%20Offers.mp4' },
      { title: 'Owner Financing', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Owner%20Financing%202.42.mp4' },
      { title: 'How We Determine Home Value', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/House%20Value%20Determination.mp4' },
      { title: 'What if I Don\u2019t Like Your Offer?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/What%20if%20I%20don_t%20like%20your%20offer.mp4' },
      { title: 'What Happens to My Equity?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/What%20Happens%20to%20My%20Equity.mp4' },
    ],
  },
  {
    id: 'situation',
    label: 'Your Situation',
    blurb: 'Common seller scenarios — liens, foundations, foreclosure, tired landlords.',
    videos: [
      { title: 'Why Sell My House?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Why%20Sell%20My%20House.mp4' },
      { title: 'Tired of Being a Landlord', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Tired%20of%20Being%20a%20Landlord.mp4' },
      { title: 'Selling a House with a Lien', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Selling%20House%20with%20Lien.mp4' },
      { title: 'Selling a House with Foundation Issues', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Selling%20House%20with%20Foundation%20Issues.mp4' },
      { title: 'Pre-Foreclosure Homes', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Will%20You%20Buy%20a%20Home%20in%20Pre-Foreclosure.mp4' },
      { title: 'What to Do With My House', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/What%20to%20do%20with%20my%20house.mp4' },
    ],
  },
  {
    id: 'closing',
    label: 'Closing & Logistics',
    blurb: 'Inspection, coordination, costs, timeline, and moving help.',
    videos: [
      { title: 'The Walk-Through', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Walk%20Through.mp4' },
      { title: 'Who Coordinates the Transaction?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Who%20Coordinates%20the%20Transaction.mp4' },
      { title: 'Who Pays Closing Costs?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Who%20Pays%20Closing%20Cost.mp4' },
      { title: 'How Fast Can I Sell?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/How%20Fast%20to%20Sell%20My%20House.mp4' },
      { title: 'Taxes When Selling', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Selling%20My%20House%20Taxes.mp4' },
      { title: 'Help With Moving Expenses', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Moving%20Expenses%20Help.mp4' },
    ],
  },
  {
    id: 'trust',
    label: 'Trust & Due Diligence',
    blurb: 'How to vet a buyer and decide if you need a realtor.',
    videos: [
      { title: 'How to Avoid Scams', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/How%20to%20Avoid%20Scams.mp4' },
      { title: 'Should I Have a Realtor?', url: 'https://tq2dbwtr6wuoq2kd.public.blob.vercel-storage.com/Should%20I%20Have%20a%20Realtor.mp4' },
    ],
  },
];

function ProcessSection() {
  const [tab, setTab] = useStateProc(PROCESS_CATEGORIES[0].id);
  const [activeIdx, setActiveIdx] = useStateProc(0);
  const [unmuted, setUnmuted] = useStateProc(false);
  const videoRef = useRefProc(null);

  const cat = PROCESS_CATEGORIES.find((c) => c.id === tab) || PROCESS_CATEGORIES[0];
  const active = cat.videos[activeIdx] || cat.videos[0];

  // Reset to first video when changing tab; reset unmuted state when video changes
  useEffectProc(() => { setActiveIdx(0); }, [tab]);
  useEffectProc(() => { setUnmuted(false); }, [active.url]);

  // Auto-pause when scrolled out of view, auto-play (muted) when in view
  useEffectProc(() => {
    if (!videoRef.current) return;
    const v = videoRef.current;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          if (v.paused) v.play().catch(() => {});
        } else {
          if (!v.paused) v.pause();
        }
      });
    }, { threshold: 0.25 });
    io.observe(v);
    return () => io.disconnect();
  }, [active.url]);

  const handleClickPlay = () => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = false;
    v.currentTime = 0;
    v.play().catch(() => {});
    setUnmuted(true);
  };

  return (
    <section id="process" className="process-section">
      <div className="process-inner">
        <div className="process-eyebrow">PROCESS</div>
        <h2 className="process-title">Watch how it works.</h2>
        <p className="process-sub">Short videos that answer the questions sellers ask us most. Pick a category, click any video.</p>

        <div className="process-tabs" role="tablist">
          {PROCESS_CATEGORIES.map((c) => (
            <button
              key={c.id}
              role="tab"
              aria-selected={tab === c.id}
              className={`process-tab ${tab === c.id ? 'is-active' : ''}`}
              onClick={() => setTab(c.id)}
              type="button"
            >
              {c.label}
              <span className="process-tab-count">{c.videos.length}</span>
            </button>
          ))}
        </div>

        <p className="process-tab-blurb">{cat.blurb}</p>

        <div className="process-stage">
          <div className={`process-player ${unmuted ? 'is-playing' : ''}`}>
            <video
              key={active.url}
              ref={videoRef}
              src={active.url}
              controls={unmuted}
              playsInline
              muted
              autoPlay
              loop={!unmuted}
              preload="metadata"
            />
            {!unmuted && (
              <button
                className="process-play"
                onClick={handleClickPlay}
                aria-label="Play with sound from beginning"
                type="button"
              >
                <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                  <path d="M10 6L25 16L10 26V6Z" fill="currentColor"/>
                </svg>
                <span className="process-play-label">Tap to play with sound</span>
              </button>
            )}
          </div>

          <div className="process-rail" role="list">
            {cat.videos.map((v, i) => (
              <button
                key={v.url + i}
                className={`process-chip ${i === activeIdx ? 'is-active' : ''}`}
                onClick={() => setActiveIdx(i)}
                type="button"
                role="listitem"
              >
                <span className="process-chip-num">{String(i + 1).padStart(2, '0')}</span>
                <span className="process-chip-label">{v.title}</span>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                  <path d="M4 3L10 7L4 11V3Z" fill="currentColor"/>
                </svg>
              </button>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

window.ProcessSection = ProcessSection;
