// screens3.jsx — HomeScreen: a scrollable, tattu-style homepage
// Sections: Hero · Core Services · SHIKI Story · Newsletter & Footer
// Exposes: HomeScreen
const { useState: useS3, useRef: useR3, useEffect: useE3 } = React;
const tr3 = (o, lang) => (o ? (o[lang] ?? o.de) : '');

function TypewriterText({ text, onComplete }) {
  const [displayed, setDisplayed] = useS3('');
  const idx = useR3(0);
  useE3(() => {
    setDisplayed('');
    idx.current = 0;
    if (!text) { if (onComplete) onComplete(); return; }
    const interval = setInterval(() => {
      setDisplayed(text.substring(0, idx.current + 1));
      idx.current++;
      if (idx.current >= text.length) {
        clearInterval(interval);
        if (onComplete) onComplete();
      }
    }, 15);
    return () => clearInterval(interval);
  }, [text]);
  return <>{displayed}</>;
}

// Hero background slides — interior is the lead image
const HERO_SLIDES = [
  { src:'assets/hero-interior.png', kind:'lounge',  pos:'center 50%' },
  { src:'assets/hero-salmon.jpg',   kind:'robata',  pos:'center 62%' },
  { src:'assets/svc-lounge-v2.png', kind:'lounge',  pos:'center 42%' },
];

// Crossfading slideshow used as the hero background
function HeroSlides({ style, fillStyle, interval = 5200 }) {
  const [idx, setIdx] = useS3(0);
  const pausedRef = useR3(false);
  useE3(() => {
    const t = setInterval(() => { if (!pausedRef.current) setIdx(i => (i + 1) % HERO_SLIDES.length); }, interval);
    return () => clearInterval(t);
  }, [interval]);
  return (
    <div className="hero-slides" style={style}>
      {HERO_SLIDES.map((s, i) => (
        <Photo key={s.src} kind={s.kind} src={s.src} pos={s.pos}
          className={'hero-slide ' + (i === idx ? 'on' : '')}
          style={{ position:'absolute', inset:0, ...fillStyle }} />
      ))}
      <div className="hero-slidedots" onMouseEnter={() => pausedRef.current = true} onMouseLeave={() => pausedRef.current = false}>
        {HERO_SLIDES.map((s, i) => (
          <button key={s.src} className={'hero-slidedot ' + (i === idx ? 'on' : '')}
            onClick={(e) => { e.stopPropagation(); setIdx(i); }} aria-label={'Slide ' + (i + 1)} />
        ))}
      </div>
    </div>
  );
}

function HomeScreen({ lang, setLang, layout = 'centered', onBook, onNavigate }) {
  const scrollRef = useR3(null);
  const servicesRef = useR3(null);
  const newsRailRef = useR3(null);
  const [nlSent, setNlSent] = useS3(false);
  const [newsIdx, setNewsIdx] = useS3(0);
  const [selectedNews, setSelectedNews] = useS3(null);

  useE3(() => {
    if (selectedNews) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [selectedNews]);

  const [servicesVisible, setServicesVisible] = useS3(false);
  useE3(() => {
    if (!servicesRef.current) return;
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setServicesVisible(true);
        observer.disconnect();
      }
    }, { threshold: 0.15 });
    observer.observe(servicesRef.current);
    return () => observer.disconnect();
  }, []);

  const storyRef = useR3(null);
  const [storyVisible, setStoryVisible] = useS3(false);
  const [storyTypingDone, setStoryTypingDone] = useS3(false);
  useE3(() => {
    if (!storyRef.current) return;
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setStoryVisible(true);
        observer.disconnect();
      }
    }, { threshold: 0.3 });
    observer.observe(storyRef.current);
    return () => observer.disconnect();
  }, []);

  const reviewsRef = useR3(null);
  const [reviewsVisible, setReviewsVisible] = useS3(false);
  useE3(() => {
    if (!reviewsRef.current) return;
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setReviewsVisible(true);
        observer.disconnect();
      }
    }, { threshold: 0.15 });
    observer.observe(reviewsRef.current);
    return () => observer.disconnect();
  }, []);

  const onNewsScroll = () => {
    const rail = newsRailRef.current; if (!rail) return;
    const card = rail.querySelector('.news-card'); if (!card) return;
    const step = card.offsetWidth + 14; // card width + gap
    setNewsIdx(Math.round(rail.scrollLeft / step));
  };
  const gotoNews = (i) => {
    const rail = newsRailRef.current; if (!rail) return;
    const card = rail.querySelector('.news-card'); if (!card) return;
    const step = card.offsetWidth + 14;
    rail.scrollTo({ left: i * step, behavior: 'smooth' });
  };

  useE3(() => {
    const interval = setInterval(() => {
      const rail = newsRailRef.current;
      if (!rail) return;
      const card = rail.querySelector('.news-card');
      if (!card) return;
      const step = card.offsetWidth + 14;
      
      const maxScroll = rail.scrollWidth - rail.clientWidth;
      if (rail.scrollLeft >= maxScroll - 5) {
        rail.scrollTo({ left: 0, behavior: 'smooth' });
      } else {
        let currentIdx = Math.round(rail.scrollLeft / step);
        rail.scrollTo({ left: (currentIdx + 1) * step, behavior: 'smooth' });
      }
    }, 2000);
    return () => clearInterval(interval);
  }, []);

  const [numNewsDots, setNumNewsDots] = useS3(SHIKI_NEWS.length);
  useE3(() => {
    const calc = () => {
      const rail = newsRailRef.current; if (!rail) return;
      const card = rail.querySelector('.news-card'); if (!card) return;
      const step = card.offsetWidth + 14;
      const maxScroll = rail.scrollWidth - rail.clientWidth;
      if (maxScroll <= 0) setNumNewsDots(0);
      else setNumNewsDots(Math.round(maxScroll / step) + 1);
    };
    calc();
    window.addEventListener('resize', calc);
    return () => window.removeEventListener('resize', calc);
  }, []);

  const scrollToServices = () => {
    const cont = scrollRef.current, el = servicesRef.current;
    if (cont && el) cont.scrollTo({ top: el.offsetTop - 8, behavior: 'smooth' });
  };

  const langToggle = (
    <button className="hero-lang" onClick={() => setLang(lang === 'de' ? 'en' : 'de')} aria-label="language">
      <Icon name="globe" size={13} />
      <span className={lang === 'de' ? 'on' : ''}>DE</span>
      <span className="lang-sep">/</span>
      <span className={lang === 'en' ? 'on' : ''}>EN</span>
    </button>
  );

  const heroMeta = (
    <div className="hero-meta">
      <div className="hero-tag">{tr3(SHIKI_STRINGS.tagline, lang)}</div>
      <div className="hero-addr">{tr3(SHIKI_STRINGS.address, lang)}</div>
    </div>
  );
  const heroCta = (
    <button className="cta-primary" onClick={onBook}>
      <span>{tr3(SHIKI_STRINGS.bookCta, lang)}</span><Icon name="chevR" size={16} />
    </button>
  );
  const scrollHint = (
    <button className="hero-hint" onClick={scrollToServices}>
      <Icon name="chevDown" size={18} />
      <span>{tr3(SHIKI_STRINGS.exploreHint, lang)}</span>
    </button>
  );

  // ── Hero section (respects heroLayout tweak) ──
  let heroSection;
  if (layout === 'split') {
    heroSection = (
      <section className="home-hero">
        <HeroSlides style={{ position:'absolute', top:0, left:0, right:0, height:'54%' }} />
        {langToggle}
        <div className="hero-splitfade" />
        <div className="hero-panel">
          <div className="hero-fade-up" style={{ animationDelay:'.1s' }}><Wordmark size={1.0} /></div>
          <div className="hero-fade-up" style={{ animationDelay:'.25s', marginTop:18 }}>{heroMeta}</div>
          <div className="hero-fade-up" style={{ animationDelay:'.4s', width:'100%', marginTop:24 }}>{heroCta}</div>
          <div className="hero-fade-up" style={{ animationDelay:'.55s', marginTop:18 }}>{scrollHint}</div>
        </div>
      </section>
    );
  } else {
    const alignBottom = layout === 'bottom';
    heroSection = (
      <section className="home-hero">
        <HeroSlides style={{ position:'absolute', inset:0 }} />
        <div className="hero-scrim" />
        {langToggle}
        <div className="hero-content" style={{ justifyContent: alignBottom ? 'flex-end' : 'center' }}>
          <div className="hero-fade-up" style={{ animationDelay:'.15s' }}><Wordmark size={alignBottom ? 1.0 : 1.12} /></div>
          <div className="hero-fade-up" style={{ animationDelay:'.32s', marginTop:18 }}>{heroMeta}</div>
          <div className="hero-fade-up" style={{ animationDelay:'.5s', width:'100%', marginTop: alignBottom ? 22 : 32 }}>{heroCta}</div>
          <div className="hero-fade-up" style={{ animationDelay:'.66s', marginTop: alignBottom ? 18 : 'auto', paddingTop: alignBottom ? 0 : 28 }}>{scrollHint}</div>
        </div>
      </section>
    );
  }

  return (
    <div className="screen home" ref={scrollRef}>
      {heroSection}

      {/* ── Section 2: Core Services ── */}
      <section className="home-services" ref={servicesRef}>
        <div className="container">
          <div className="sec-kicker-row">
            <span className="sec-kicker">{tr3(SHIKI_STRINGS.coreKicker, lang)}</span>
            <span className="sec-kicker-rule" />
          </div>
          <div className="svc-stack">
            {SHIKI_SERVICES.map((s, i) => {
              let animClass = '';
              if (servicesVisible) {
                if (i === 0) animClass = 'slide-in-left';
                else if (i === 2) animClass = 'slide-in-right';
                else animClass = 'slide-up-card';
              }
              return (
                <button key={s.id} className={`svc-card ${animClass}`} onClick={() => onNavigate(s.target)} style={{ opacity: servicesVisible ? undefined : 0 }}>
                  <Photo kind={s.photo} src={s.img} pos={s.pos} style={{ position:'absolute', inset:0 }} />
                  <div className="svc-grad" />
                  <div className="svc-body">
                    <div className="svc-index">0{i + 1}</div>
                    <div className="svc-title">{tr3(s.title, lang)}</div>
                    <div className="svc-line">{tr3(s.line, lang)}</div>
                    <div className="svc-go">
                      <span>{lang === 'de' ? 'Entdecken' : 'Explore'}</span><Icon name="chevR" size={14} />
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── Section 3: The SHIKI Story ── */}
      <section className="home-story" ref={storyRef}>
        <div className="container">
          <div className="story-kanji">四季</div>
          <div className="sec-kicker" style={{ textAlign:'center' }}>{tr3(SHIKI_STRINGS.storyKicker, lang)}</div>
          <h2 className="story-title">{tr3(SHIKI_STRINGS.storyTitle, lang)}</h2>
          <span className="story-rule" />
          <p className="story-body" style={{ minHeight: '80px' }}>
            {storyVisible ? (
              <TypewriterText text={tr3(SHIKI_STRINGS.storyBody, lang)} onComplete={() => setStoryTypingDone(true)} />
            ) : null}
          </p>
          <button 
            className="story-about-btn" 
            style={{ opacity: storyTypingDone ? 1 : 0, transition: 'opacity 0.6s ease', pointerEvents: storyTypingDone ? 'auto' : 'none' }}
            onClick={() => onNavigate('about')}>
            <span>{tr3(SHIKI_STRINGS.moreAbout, lang).toUpperCase()}</span><Icon name="chevR" size={14} />
          </button>
        </div>
      </section>

      {/* ── Section 3.5: Featured news / journal (horizontal slider) ── */}
      <section className="home-news">
        <div className="news-head">
          <div>
            <div className="sec-kicker">{tr3(SHIKI_STRINGS.newsKicker, lang)}</div>
            <h2 className="news-title">{tr3(SHIKI_STRINGS.newsTitle, lang)}</h2>
          </div>
        </div>
        <div className="news-rail" ref={newsRailRef} onScroll={onNewsScroll}>
          {SHIKI_NEWS.map((n) => (
            <article key={n.id} className="news-card" onClick={() => setSelectedNews(n)} style={{ cursor: 'pointer' }} role="button" tabIndex={0}>
              <Photo kind={n.photo || 'sushi'} src={n.img} pos={n.pos} style={{ position:'absolute', inset:0 }} />
              <div className="news-grad" />
              <span className="news-cat">{tr3(n.cat, lang)}</span>
              <div className="news-body">
                <div className="news-date">{tr3(n.date, lang)}</div>
                <h3 className="news-cardtitle">{tr3(n.title, lang)}</h3>
                <div className="news-more">
                  <span>{tr3(SHIKI_STRINGS.readMore, lang)}</span><Icon name="chevR" size={13} />
                </div>
              </div>
            </article>
          ))}
          <div className="news-railpad" />
        </div>
        <div className="news-dots">
          {Array.from({ length: numNewsDots }).map((_, i) => (
            <button key={i} className={'news-dot ' + (i === newsIdx ? 'on' : '')}
              onClick={() => gotoNews(i)} aria-label={'Slide ' + (i + 1)} />
          ))}
        </div>
      </section>

      {/* ── Section 4: Reviews, Newsletter & Footer ── */}
      <section className="home-footer">
        
        {/* Reviews Testimonial Carousel */}
        <div className="reviews-block" ref={reviewsRef}>
          <div className="reviews-header" style={{
            opacity: reviewsVisible ? 1 : 0,
            transform: reviewsVisible ? 'translateY(0)' : 'translateY(20px)',
            transition: 'all 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0s'
          }}>
            <h3 className="reviews-title">4.8</h3>
            <div className="reviews-header-info">
              <div className="sec-kicker" style={{ textAlign: 'left', paddingLeft: 0, marginBottom: '8px' }}>
                {tr3(SHIKI_STRINGS.revKicker, lang)}
              </div>
              <div className="reviews-stars">
                {[1,2,3,4,5].map(i => <Icon key={i} name="starFill" size={20} style={{ fill: 'var(--gold)' }} />)}
              </div>
              <div className="reviews-count">
                <Icon name="google" size={14} style={{ marginRight: 6 }} />
                {tr3(SHIKI_STRINGS.revCount, lang)}
              </div>
            </div>
          </div>
          
          <div className="rev-slider">
            {SHIKI_REVIEWS.map((r, i) => (
              <div key={r.id} className="rev-card" style={{
                opacity: reviewsVisible ? 1 : 0,
                transform: reviewsVisible ? 'translateY(0)' : 'translateY(40px)',
                transition: `all 0.6s cubic-bezier(0.16, 1, 0.3, 1) ${i * 0.15 + 0.2}s`
              }}>
                <div className="rev-card-header">
                  <div className="rev-card-avatar">{r.author.charAt(0)}</div>
                  <div className="rev-card-meta">
                    <div className="rev-card-author">{r.author}</div>
                    <div className="rev-card-guide">Local Guide</div>
                  </div>
                  <Icon name="google" size={16} style={{ marginLeft: 'auto', color: 'var(--bone-2)' }} />
                </div>
                <div className="rev-card-stars">
                  {[1,2,3,4,5].map(i => <Icon key={i} name="starFill" size={12} style={{ fill: 'var(--gold)' }} />)}
                  <span className="rev-card-time">{tr3(r.time, lang)}</span>
                </div>
                <div className="rev-card-text">"{tr3(r.text, lang)}"</div>
              </div>
            ))}
          </div>
        </div>

        <div className="nl-block">
          <div className="nl-content">
            <div className="sec-kicker" style={{ textAlign: 'left', marginBottom: '8px' }}>{tr3(SHIKI_STRINGS.nlKicker, lang)}</div>
            <h3 className="nl-title" style={{ textAlign: 'left', margin: 0 }}>{tr3(SHIKI_STRINGS.nlTitle, lang)}</h3>
          </div>
          <div className="nl-form-wrapper">
            <form className="nl-form" onSubmit={(e) => { e.preventDefault(); setNlSent(true); e.target.reset(); setTimeout(() => setNlSent(false), 3000); }}>
              <div className="nl-inputwrap">
                <Icon name="mail" size={16} />
                <input className="nl-input" type="email" required
                  placeholder={tr3(SHIKI_STRINGS.nlPlaceholder, lang)} aria-label="email" />
              </div>
              <button className="nl-btn" type="submit">
                <span>{tr3(SHIKI_STRINGS.nlButton, lang)}</span>
              </button>
            </form>
          </div>
        </div>

        <div className="foot-grid">
          <div className="foot-col">
            <div className="foot-label">{tr3(SHIKI_STRINGS.hoursLabel, lang)}</div>
            {SHIKI_HOURS[lang].map((h, i) => (
              <div key={i} className="foot-hours-row">
                <span>{h[0]}</span><span className="foot-hours-val">{h[1]}</span>
              </div>
            ))}
          </div>
          <div className="foot-col">
            <div className="foot-label">{tr3(SHIKI_STRINGS.addrLabel, lang)}</div>
            <div className="foot-addr"><span className="addr-l1">Klostergasse 18</span><span className="addr-l2">04109 Leipzig</span></div>
          </div>
        </div>

        <div className="foot-map">
          <iframe
            title="SHIKI Leipzig — Klostergasse 18"
            src="https://www.google.com/maps?q=Klostergasse+18,+04109+Leipzig&z=16&output=embed"
            loading="lazy" referrerPolicy="no-referrer-when-downgrade"
            allowFullScreen="" />
          <a className="foot-maps" href={SHIKI_MAPS_URL} target="_blank" rel="noreferrer">
            <Icon name="pin" size={14} /><span>{tr3(SHIKI_STRINGS.directions, lang)}</span>
          </a>
        </div>
      </section>

      <SiteFooter lang={lang} onNavigate={onNavigate} noPadBottom />

      {selectedNews && ReactDOM.createPortal(
        <div className="news-modal-overlay" onClick={() => setSelectedNews(null)}>
          <div className="news-modal" onClick={(e) => e.stopPropagation()}>
            <button className="news-modal-close" onClick={() => setSelectedNews(null)} aria-label="Close modal">
              <Icon name="close" size={16} />
            </button>
            <div className="news-modal-scroll">
              <div className="news-modal-img">
                <Photo kind={selectedNews.photo || 'sushi'} src={selectedNews.img} pos={selectedNews.pos} style={{ position:'absolute', inset:0 }} />
                <div className="news-grad" />
              </div>
              <div className="news-modal-body">
                <div className="news-modal-cat">
                  <span>{tr3(selectedNews.cat, lang)}</span>
                  <span>{tr3(selectedNews.date, lang)}</span>
                </div>
                <h2 className="news-modal-title">{tr3(selectedNews.title, lang)}</h2>
                {selectedNews.content && tr3(selectedNews.content, lang).split('\n\n').map((para, i) => (
                  <p key={i} className="news-modal-text">{para}</p>
                ))}
              </div>
            </div>
          </div>
        </div>,
        document.getElementById('stage')
      )}

      {nlSent && ReactDOM.createPortal(
        <div className="shiki-toast">
          <Icon name="check" size={16} style={{ color: 'var(--gold)' }} />
          <span>{tr3(SHIKI_STRINGS.nlDone, lang)}</span>
        </div>,
        document.getElementById('stage')
      )}
    </div>
  );
}

Object.assign(window, { HomeScreen });
