// Wochenangebote — Hero-Card links + Karussell rechts.
// Daten kommen live aus /api/offers/current (DreamCRM-Push). Wenn kein
// aktuelles Angebot im KV liegt (z.B. zwischen zwei Wochen oder vor dem
// ersten Push), wird die ganze Section ausgeblendet — kein Hardcoded-Fallback.
function Angebote() {
  const { t, lang } = useT();
  const [remote, setRemote] = React.useState(null);
  const [tried, setTried] = React.useState(false);
  const [idx, setIdx] = React.useState(0);
  const trackRef = React.useRef(null);
  const cardW = 240;
  const gap = 16;
  const step = cardW + gap;
  const visible = 3;

  // Laden + aktuell halten. Safari (v.a. iOS) restauriert Tabs aus dem
  // BFCache: der alte React-State (inkl. alter pdf_url aufs alte Prospekt-
  // Blob) lebt dann weiter, ohne dass dieser Mount-Effect je wieder läuft.
  // Darum zusätzlich bei pageshow(persisted) und beim Sichtbarwerden des
  // Tabs neu fetchen — gedrosselt auf 1×/Minute. setRemote nur bei wirklich
  // neuem Push (published_at), sonst würde jeder Tab-Wechsel das Karussell
  // auf Slide 0 zurückwerfen (Effect unten hängt an `remote`).
  const lastFetchRef = React.useRef(0);
  React.useEffect(() => {
    let alive = true;
    const load = () => {
      lastFetchRef.current = Date.now();
      fetch('/api/offers/current', { headers: { Accept: 'application/json' }, cache: 'no-store' })
        .then((r) => (r.ok ? r.json() : null))
        .then((json) => {
          if (!alive) return;
          if (json && json.ok && json.offer) {
            setRemote((prev) => (
              prev && prev.published_at && prev.published_at === json.offer.published_at
                ? prev
                : json.offer
            ));
          }
        })
        .catch(() => {})
        .finally(() => { if (alive) setTried(true); });
    };
    const reloadIfStale = () => {
      if (document.visibilityState !== 'visible') return;
      if (Date.now() - lastFetchRef.current < 60000) return;
      load();
    };
    const onPageShow = (e) => { if (e.persisted) reloadIfStale(); };
    load();
    window.addEventListener('pageshow', onPageShow);
    document.addEventListener('visibilitychange', reloadIfStale);
    return () => {
      alive = false;
      window.removeEventListener('pageshow', onPageShow);
      document.removeEventListener('visibilitychange', reloadIfStale);
    };
  }, []);

  // Sync `idx` mit nativem Scroll (Touch-Swipe / Trackpad / Maus)
  React.useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const next = Math.round(Math.abs(el.scrollLeft) / step);
        setIdx((prev) => (prev === next ? prev : next));
      });
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      el.removeEventListener('scroll', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [step, remote]);

  // Wenn neue CRM-Daten kommen: zurueck auf Slide 0 (instant, ohne Animation)
  React.useEffect(() => {
    if (!remote) return;
    setIdx(0);
    if (trackRef.current) trackRef.current.scrollLeft = 0;
  }, [remote]);

  // Solange noch nichts geladen ist (oder nichts gepusht wurde) → Section verbergen.
  if (!tried) return null;
  if (!remote || !Array.isArray(remote.produkte) || remote.produkte.length === 0) return null;

  const produkte = remote.produkte;
  const heroId = remote.hero_produkt_id;
  const hero = produkte.find((p) => p.id === heroId) || produkte[0];
  const rest = produkte.filter((p) => p !== hero);
  const max = Math.max(0, rest.length - visible);
  const go = (n) => {
    const target = Math.min(max, Math.max(0, n));
    setIdx(target);
    const el = trackRef.current;
    if (el) el.scrollTo({ left: target * step, behavior: 'smooth' });
  };

  // KW-Label live aus dem Push. Fallback: clientseitig berechnete KW
  // wie früher — falls die CRM-Übersetzung mal ausfällt.
  const kwLabel = remote.kw_label_translations && remote.kw_label_translations[lang]
    ? remote.kw_label_translations[lang]
    : (remote.kw || '');

  const headline = (remote.headline_translations && remote.headline_translations[lang])
    || t('angebote.headline');
  const headlineEm = t('angebote.headlineEm');
  const hIdx = headline.indexOf(headlineEm);
  const hBefore = hIdx >= 0 ? headline.slice(0, hIdx) : headline;
  const hAfter  = hIdx >= 0 ? headline.slice(hIdx + headlineEm.length) : '';

  // Hilfs-Selector pro Produkt: bevorzugt Übersetzung in der aktiven Sprache,
  // fällt sonst auf de zurück.
  const tr = (p, key) => {
    const t = p.translations || {};
    return (t[lang] && t[lang][key]) || (t.de && t.de[key]) || '';
  };

  const heroName = tr(hero, 'name');
  const heroSub  = tr(hero, 'sub');
  const heroEyebrow = tr(hero, 'eyebrow');
  const heroUnit = tr(hero, 'unit');
  const heroColor = hero.color || '#7A2E1F';
  const heroImage = hero.image_url || '';

  const flyerHref = remote.pdf_url || '';
  const flyerName = remote.pdf_filename || `Azra-Wochenangebote-${remote.slug || 'aktuell'}.pdf`;

  return (
    <section id="angebote" style={{ background:'var(--bg-2)', paddingTop:48, paddingBottom:48 }}>
      <div className="container">
        <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:24, marginBottom:24, flexWrap:'wrap' }}>
          <div>
            <span className="eyebrow">{kwLabel}</span>
            <h2 style={{ marginTop:8 }}>{hBefore}<span className="hand" style={{ color:'var(--brick)', fontSize:'1.15em', display:'inline-block', transform:'rotate(-2deg)' }}>{headlineEm}</span>{hAfter}</h2>
          </div>
          <div style={{ display:'flex', gap:10, alignItems:'center' }}>
            <button onClick={()=>go(idx-1)} disabled={idx===0} className="btn ghost" style={{ padding:'12px', borderRadius:'50%', opacity:idx===0?.4:1 }} aria-label={t('common.back')}><Icon name="chev_l" size={18} className="icon-flip-rtl"/></button>
            <button onClick={()=>go(idx+1)} disabled={idx>=max} className="btn ghost" style={{ padding:'12px', borderRadius:'50%', opacity:idx>=max?.4:1 }} aria-label={t('common.next')}><Icon name="chev_r" size={18} className="icon-flip-rtl"/></button>
            {flyerHref
              ? <a href={flyerHref} download={flyerName} target="_blank" rel="noreferrer" className="btn" style={{ marginInlineStart:8, padding:'12px 18px', fontSize:13 }}>{t('angebote.flyer')}</a>
              : null}
          </div>
        </div>

        <div className="deals-grid">
          {/* Hero-Card: Angebot der Woche */}
          <article className="deal-card" style={{ position:'relative', background:'var(--paper)' }}>
            {/* contain statt cover: Produkt komplett sichtbar (freigestellt), wie auf dem
                CRM-Angebotszettel. #FAF6EA = Paper-Ton, den der CRM-Push in die JPEGs backt
                — so sitzt das Bild nahtlos, ohne Letterbox-Kanten. */}
            {heroImage
              ? <div className="deal-media deal-media-hero"><ResponsiveImg src={heroImage} alt={heroName} sizes="(min-width: 900px) 40vw, 100vw" style={{ width:'100%', height:'100%', objectFit:'contain', display:'block' }}/></div>
              : <div className="deal-media deal-media-hero ph" data-ph={heroName}></div>
            }
            <div className="price-stamp price-stamp-hero ltr" style={{ background:heroColor }}>
              <div className="big">{hero.price}€</div>
              <div className="small">{heroUnit}</div>
            </div>
            <div style={{ position:'absolute', top:16, insetInlineStart:16, background:'var(--ink)', color:'var(--paper)', padding:'7px 12px', borderRadius:999, fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'.14em', textTransform:'uppercase' }}>
              {t('angebote.heroBadge')}
            </div>
            <div style={{ padding:'18px 22px 20px' }}>
              <div className="eyebrow" style={{ color:'var(--gold-deep)' }}>{heroEyebrow}</div>
              <h3 style={{ marginTop:6, fontSize:30 }}>{heroName}</h3>
              <p style={{ color:'var(--ink-2)', fontSize:14, marginTop:8 }}>{heroSub}</p>
              <div style={{ marginTop:14, display:'flex', alignItems:'baseline', gap:14 }}>
                {hero.old_price && <span className="ltr" style={{ textDecoration:'line-through', color:'var(--ink-2)', fontSize:14 }}>{t('angebote.insteadOf', { price: hero.old_price })}</span>}
                <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'var(--gold-deep)', marginInlineStart:'auto' }}>{t('angebote.onlyThisWeek')}</span>
              </div>
            </div>
          </article>

          {/* Karussell mit Rest — nativ scrollbar (Touch/Wheel) + scroll-snap */}
          <div className="deals-track-wrap">
            <div ref={trackRef} className="deals-track">
              {rest.map((d) => {
                const name = tr(d, 'name');
                const sub  = tr(d, 'sub');
                const eyebrow = tr(d, 'eyebrow');
                const unit = tr(d, 'unit');
                const color = d.color || '#9C3E2C';
                const img = d.image_url || '';
                return (
                  <article key={d.id} className="deal-card deals-track-item" style={{ width:cardW, flex:'0 0 auto', position:'relative' }}>
                    {img
                      ? <div className="deal-media"><ResponsiveImg src={img} alt={name} sizes="240px" style={{ width:'100%', height:'100%', objectFit:'contain', display:'block' }}/></div>
                      : <div className="deal-media ph" data-ph={name}></div>
                    }
                    <div className="price-stamp ltr" style={{ background:color }}>
                      <div className="big">{d.price}€</div>
                      <div className="small">{unit}</div>
                    </div>
                    <div style={{ padding:'14px 16px 16px' }}>
                      <div className="eyebrow" style={{ color:'var(--gold-deep)', fontSize:10 }}>{eyebrow}</div>
                      <h3 style={{ marginTop:6, fontSize:18 }}>{name}</h3>
                      <p style={{ color:'var(--ink-2)', fontSize:12, marginTop:4 }}>{sub}</p>
                      {d.old_price && <div style={{ marginTop:8 }}><span className="ltr" style={{ textDecoration:'line-through', color:'var(--ink-2)', fontSize:12 }}>{t('angebote.insteadOf', { price: d.old_price })}</span></div>}
                    </div>
                  </article>
                );
              })}
            </div>
          </div>
        </div>

        {rest.length > visible ? (
          <div style={{ marginTop:20, display:'flex', gap:6, justifyContent:'center' }}>
            {Array.from({length:max+1}).map((_,i)=>(
              <button key={i} onClick={()=>go(i)} aria-label={`Slide ${i+1}`}
                style={{ width:i===idx?28:8, height:8, border:0, borderRadius:4, background:i===idx?'var(--ink)':'var(--line)', transition:'all .3s', padding:0 }}/>
            ))}
          </div>
        ) : null}
      </div>

      <style>{`
        /* Feste Bild-Box wie die CRM-Angebotszettel-Kachel: definierte Höhe
           über aspect-ratio + object-fit:contain. Jedes Produkt — quer
           (Fleisch) wie hoch (Flaschen/Gläser, z.B. Sucuk 227×800) — sitzt in
           einer einheitlichen Box auf #FAF6EA, ohne die Karte aufzublähen.
           Vorher: flex:1 + <img height:100%> ohne feste Höhe → das höchste Bild
           streckte im align-items:stretch-Track ALLE Karten und ließ die
           Querformat-Bilder winzig in der Leerfläche schweben. */
        .deal-media{ flex:0 0 auto; aspect-ratio:1 / 1; background:#FAF6EA; border-bottom:1px solid var(--line); overflow:hidden; padding:10px; box-sizing:border-box; }
        .deal-media img{ width:100%; height:100%; object-fit:contain; display:block; }
        .deal-media-hero{ aspect-ratio:4 / 3; padding:12px; }
        .deals-grid{ display:grid; grid-template-columns:1fr; gap:16px; align-items:stretch; }
        .deals-track-wrap{ position:relative; min-width:0; }
        .deals-track{
          display:flex; gap:16px;
          overflow-x:auto; overflow-y:hidden;
          scroll-snap-type:x mandatory;
          scroll-behavior:smooth;
          -webkit-overflow-scrolling:touch;
          overscroll-behavior-inline:contain;
          padding-bottom:6px;
        }
        .deals-track-item{ scroll-snap-align:start; }
        /* Dezente Scrollbar auf Desktop, ausblenden auf Mobile */
        .deals-track::-webkit-scrollbar{ height:6px; }
        .deals-track::-webkit-scrollbar-track{ background:transparent; }
        .deals-track::-webkit-scrollbar-thumb{ background:var(--line); border-radius:3px; }
        .deals-track{ scrollbar-width:thin; scrollbar-color:var(--line) transparent; }
        @media (max-width: 599px){
          .deals-track{ scrollbar-width:none; padding-bottom:0; }
          .deals-track::-webkit-scrollbar{ display:none; }
        }
        @media (prefers-reduced-motion: reduce){
          .deals-track{ scroll-behavior:auto; }
        }
        .price-stamp-hero{ width:84px; height:84px; top:10px; right:10px; }
        .price-stamp-hero .big{ font-size:22px; }
        .deal-card .price-stamp:not(.price-stamp-hero){ width:64px; height:64px; top:10px; right:10px; }
        .deal-card .price-stamp:not(.price-stamp-hero) .big{ font-size:15px; }
        .deal-card .price-stamp:not(.price-stamp-hero) .small{ font-size:8px; }
        @media (min-width: 600px){
          .deals-grid{ gap:18px; }
          .price-stamp-hero{ width:96px; height:96px; top:12px; right:12px; }
          .price-stamp-hero .big{ font-size:24px; }
          .deal-card .price-stamp:not(.price-stamp-hero){ width:74px; height:74px; }
          .deal-card .price-stamp:not(.price-stamp-hero) .big{ font-size:18px; }
        }
        @media (min-width: 900px){
          .deals-grid{ grid-template-columns:1.15fr 2fr; gap:20px; }
          .price-stamp-hero{ width:110px; height:110px; top:16px; right:16px; }
          .price-stamp-hero .big{ font-size:28px; }
          .deal-card .price-stamp:not(.price-stamp-hero){ width:84px; height:84px; top:14px; right:14px; }
          .deal-card .price-stamp:not(.price-stamp-hero) .big{ font-size:22px; }
          .deal-card .price-stamp:not(.price-stamp-hero) .small{ font-size:9px; }
        }
      `}</style>
    </section>
  );
}
window.Angebote = Angebote;
