// GrubSlider.jsx — auto-rotating regional hot-dog carousel on mustard canvas.
// Images are sourced from Loremflickr using tag queries — it returns real Flickr
// food photos for the given tag set. If an image fails, we fall back to the
// regional color tile (no broken-image icon is ever shown).
const imgUrl = (tag, seed) =>
  `https://loremflickr.com/800/1000/${encodeURIComponent(tag)}/?lock=${seed}`;

const SLIDES = [
  {title:'The Snap Dog',      region:'Brooklyn, NY',      note:'Natural-casing all-beef, blistered over lump charcoal.',                c:'#8a2b1c', q:'brooklyn snap hot dog natural casing',   tag:'hotdog,charcoal,grill',         seed:11},
  {title:'Chicago Drag',      region:'Chicago, IL',       note:'Poppy-seed bun. Sport peppers. Zero ketchup — ever.',                   c:'#3c5a2a', q:'chicago style hot dog poppy seed bun',   tag:'chicago,hotdog,poppyseed',      seed:12},
  {title:'Sonoran Wrap',      region:'Tucson, AZ',        note:'Bacon-wrapped, pinto beans, jalapeño salsa, bolillo bun.',              c:'#6b3a1c', q:'sonoran hot dog bacon wrapped',          tag:'sonoran,hotdog,bacon',          seed:13},
  {title:'Coney Chili',       region:'Detroit, MI',       note:'Loose chili, mustard, raw onion. Three at 2 a.m.',                      c:'#5a3520', q:'detroit coney island hot dog chili',     tag:'coney,hotdog,chili',            seed:14},
  {title:'Water Dog',         region:'Manhattan, NY',     note:'Dirty-water frank, sauerkraut, street onions. No apologies.',           c:'#7a5a28', q:'new york dirty water hot dog street cart',tag:'newyork,hotdog,cart',           seed:15},
  {title:'Kansas City Reuben',region:'Kansas City, MO',   note:'Sauerkraut, swiss, Thousand Island on a toasted sesame bun.',           c:'#6b4a28', q:'kansas city reuben hot dog sauerkraut',  tag:'reuben,hotdog,sauerkraut',      seed:16},
  {title:'The Seattle Dog',   region:'Seattle, WA',       note:'Cream cheese, grilled onions, jalapeños. Post-bar canon.',              c:'#4a5f6a', q:'seattle hot dog cream cheese grilled onions',tag:'seattle,hotdog,creamcheese',seed:17},
  {title:'The Slaw Dog',      region:'Charleston, WV',    note:'West Virginia-style: chili, mustard, onion, and coleslaw.',             c:'#5c6a2a', q:'west virginia slaw dog coleslaw chili',  tag:'slaw,hotdog,coleslaw',          seed:18},
  {title:'The Half-Smoke',    region:'Washington, D.C.',  note:"Smoked half pork / half beef. Onions, mustard, chili. Ben's law.",      c:'#6a3528', q:"ben's chili bowl half smoke washington dc",tag:'halfsmoke,hotdog,smoked',      seed:19},
  {title:'The Ripper',        region:'Clifton, NJ',       note:"Deep-fried until the casing blows wide open. Rutt's rule.",             c:'#8a3a1c', q:"rutt's hut ripper deep fried hot dog",   tag:'deepfried,hotdog,fried',        seed:20},
  {title:'Texas Tommy',       region:'Philadelphia, PA',  note:'Bacon-wrapped, stuffed with American cheese. Philly diner classic.',    c:'#7a4a28', q:'texas tommy hot dog bacon cheese philadelphia',tag:'bacon,cheese,hotdog',       seed:21},
  {title:'The Red Snapper',   region:'Bangor, ME',        note:'Bright-red natural-casing Maine dog. Split-top New England bun.',       c:'#8a2020', q:'maine red snapper hot dog split top bun',tag:'maine,hotdog,red',              seed:22},
  {title:'The Michigan',      region:'Plattsburgh, NY',   note:'Steamed bun, meat sauce, mustard, onion. Not to be confused.',          c:'#5a3a20', q:'plattsburgh michigan hot dog meat sauce',tag:'hotdog,meatsauce,bun',          seed:23},
  {title:'The Tex-Mex Dog',   region:'San Antonio, TX',   note:'Bacon-wrapped, pickled jalapeños, pinto beans, cotija.',                c:'#6a4828', q:'tex mex hot dog san antonio bacon wrapped',tag:'texmex,hotdog,jalapeno',      seed:24},
  {title:'The Luther',        region:'Atlanta, GA',       note:'Glazed donut instead of a bun. Bacon. Sweetness meets smoke.',          c:'#7a5520', q:'luther hot dog glazed donut bun',        tag:'donut,hotdog,glazed',           seed:25},
  {title:'Puka Dog',          region:'Honolulu, HI',      note:'Hawaiian sweet bun speared hole-through. Tropical relish.',             c:'#8a5a20', q:'puka hot dog hawaii tropical relish',    tag:'hawaii,hotdog,tropical',        seed:26},
  {title:'The Mission Dog',   region:'San Francisco, CA', note:'Bacon-wrapped street dog. Grilled peppers, onions, mayo.',              c:'#6a3a28', q:'san francisco mission street hot dog bacon',tag:'sanfrancisco,hotdog,bacon',  seed:27},
  {title:'Minneapolis Juicy', region:'Minneapolis, MN',   note:'Cheese-stuffed frank, split and grilled. Bun is a formality.',          c:'#7a5528', q:'juicy cheese stuffed hot dog minneapolis',tag:'cheesestuffed,hotdog,grilled',seed:28},
  {title:"The Pink's",        region:'Los Angeles, CA',   note:'Chili-cheese stretch dog. Nine-inch frank, warm steamed bun.',          c:'#8a3825', q:"pink's hot dog los angeles chili cheese",tag:'chili,cheese,hotdog',           seed:29},
  {title:'The Carolina Slaw', region:'Charlotte, NC',     note:'Chili, mustard, slaw, onion. Steamed bun. Southern gospel.',            c:'#6a5528', q:'carolina hot dog chili slaw mustard onion',tag:'carolina,hotdog,slaw',        seed:30},
].map(s => ({...s, img: imgUrl(s.tag, s.seed)}));

function GrubSlider(){
  const [loaded,setLoaded] = React.useState(false);
  const [paused,setPaused] = React.useState(false);
  const scrollerRef = React.useRef(null);

  React.useEffect(()=>{const t=setTimeout(()=>setLoaded(true),80);return ()=>clearTimeout(t)},[]);

  // Slow auto-rotate: ~80px/sec, infinite loop via duplicate set
  React.useEffect(()=>{
    if(paused) return;
    const el = scrollerRef.current; if(!el) return;
    let raf, last = performance.now();
    const tick = (now)=>{
      const dt = now - last; last = now;
      if(!paused && el){
        el.scrollLeft += (80 * dt/1000); // 80px per second
        // wrap at halfway (since we render SLIDES twice)
        const half = el.scrollWidth / 2;
        if(el.scrollLeft >= half){ el.scrollLeft -= half; }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return ()=>cancelAnimationFrame(raf);
  },[paused]);

  const scrollBy = (dir)=>{
    const el = scrollerRef.current; if(!el) return;
    el.scrollBy({left: dir * (el.clientWidth * 0.7), behavior:'smooth'});
  };

  const searchUrl = (q)=>`https://www.google.com/search?tbm=isch&q=${encodeURIComponent(q)}`;
  const loopSlides = [...SLIDES, ...SLIDES];

  return (
    <section className="bento grain" style={{background:'#0D0D0D',color:'#F5E6C4',border:'1px solid rgba(0,0,0,.1)',paddingTop:24}}>
      <span className="tape">Field Log // Regional</span>
      <div className="flex flex-col items-start justify-between gap-4" style={{marginBottom:12,paddingTop:20,flexWrap:'wrap'}}>
        <div style={{flex:1,minWidth:260}}>
          <p className="eyebrow" style={{color:'#FFC107'}}>The Grub Slider</p>
          <h2 className="display" style={{fontSize:'clamp(3rem,6vw,4.5rem)',marginTop:8,marginBottom:0,color:'#F5E6C4'}}>Twenty dogs.<br /><span style={{color:'var(--grub-ketchup)'}}>Twenty verdicts.</span></h2>
        </div>
        <div className="flex items-center gap-3" style={{alignSelf:'flex-end',marginTop:-8}}>
          <button onClick={()=>scrollBy(-1)} className="gs-nav-btn" aria-label="Previous">←</button>
          <button onClick={()=>scrollBy(1)} className="gs-nav-btn" aria-label="Next">→</button>
        </div>
      </div>
      <div
        ref={scrollerRef}
        className="hide-scrollbar flex gap-5"
        style={{overflowX:'auto',paddingBottom:8,margin:'0 -8px',paddingLeft:8,paddingRight:8,scrollBehavior:'auto'}}
        onMouseEnter={()=>setPaused(true)}
        onMouseLeave={()=>setPaused(false)}
        onTouchStart={()=>setPaused(true)}
        onTouchEnd={()=>setTimeout(()=>setPaused(false),2000)}
      >
        {loopSlides.map((s,i)=>(
          <a key={i} href={searchUrl(s.q)} target="_blank" rel="noopener"
             className="slide-card" style={{
            aspectRatio:'4/5',width:'30%',minWidth:260,flex:'none',position:'relative',overflow:'hidden',borderRadius:16,border:'1px solid rgba(255,193,7,.12)',background:'#1B1B1B',cursor:'pointer',textDecoration:'none',
            opacity: loaded?1:0,transform: loaded?'translateY(0)':'translateY(40px)',transition:`opacity .7s var(--ease-grub) ${Math.min(i,8)*100}ms,transform .7s var(--ease-grub) ${Math.min(i,8)*100}ms,box-shadow 200ms var(--ease-grub)`
          }}>
            {/* Fallback color layer underneath the image */}
            <div style={{position:'absolute',inset:0,background:`linear-gradient(135deg, ${s.c}, #1a1a1a 85%)`}} />
            <div aria-hidden style={{position:'absolute',inset:0,opacity:.2,backgroundImage:'repeating-linear-gradient(45deg, rgba(255,255,255,.06) 0 2px, transparent 2px 14px)'}} />
            {/* Real photo — falls back silently if load fails */}
            <img
              src={s.img}
              alt={`${s.title} — ${s.region}`}
              loading="lazy"
              referrerPolicy="no-referrer"
              onError={(e)=>{ e.currentTarget.style.display='none'; }}
              style={{position:'absolute',inset:0,width:'100%',height:'100%',objectFit:'cover',zIndex:1}}
            />
            {/* Bottom-to-top dark overlay so text remains legible */}
            <div style={{position:'absolute',inset:0,zIndex:2,background:'linear-gradient(0deg, #0D0D0D 10%, rgba(13,13,13,.55) 50%, rgba(13,13,13,.1) 100%)'}} />
            <div className="grub-search-chip" aria-hidden>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{height:14,width:14}}>
                <circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>
              </svg>
              Google Images
            </div>
            <div style={{position:'absolute',zIndex:3,left:20,right:20,bottom:20}}>
              <div className="flex items-center gap-2" style={{marginBottom:12,fontFamily:'var(--font-mono)',fontSize:'.65rem',textTransform:'uppercase',letterSpacing:'.26em',color:'#FFC107'}}>
                <span style={{height:1,width:20,background:'#FFC107'}} />{s.region}
                <span style={{marginLeft:'auto',borderRadius:9999,background:'var(--grub-ketchup)',padding:'2px 8px',fontSize:'.6rem',color:'#fff'}}>{String((i%SLIDES.length)+1).padStart(2,'0')}</span>
              </div>
              <h3 className="display" style={{fontSize:'1.75rem',color:'#F5E6C4'}}>{s.title}</h3>
              <p style={{marginTop:8,fontSize:'.875rem',color:'rgba(245,230,196,.85)',lineHeight:1.5}}>{s.note}</p>
            </div>
          </a>
        ))}
      </div>
      <style>{`
        .gs-nav-btn{display:grid;place-items:center;height:48px;width:48px;border-radius:9999px;border:1px solid rgba(255,193,7,.2);background:#1B1B1B;color:#F5E6C4;transition:all 200ms var(--ease-grub);cursor:pointer;font-size:18px}
        .gs-nav-btn:hover{transform:scale(1.05);border-color:#FFC107;color:#FFC107}
        .slide-card:hover{ transform: translateY(-4px) !important; box-shadow: 0 20px 40px -20px rgba(211,47,47,.5); }
        .grub-search-chip{
          position:absolute; top:16px; right:16px; z-index:4;
          display:inline-flex; align-items:center; gap:6px;
          padding:6px 10px; border-radius:9999px;
          background: rgba(13,13,13,.72); backdrop-filter: blur(8px);
          border:1px solid rgba(255,193,7,.2);
          color: #FFC107;
          font-family: var(--font-mono); font-size:.6rem; text-transform:uppercase; letter-spacing:.2em;
          opacity:0; transition: opacity 200ms var(--ease-grub);
        }
        .slide-card:hover .grub-search-chip{ opacity:1 }
      `}</style>
    </section>
  );
}
window.GrubSlider = GrubSlider;
