// Päikeseraja talu — main app

const { useState, useEffect, useMemo, useRef } = React;

function App() {
  const [lang, setLang] = useState('et');
  const [navScrolled, setNavScrolled] = useState(false);
  const [navTransparent, setNavTransparent] = useState(true);
  const [range, setRange] = useState({ from: null, to: null });
  const [modal, setModal] = useState(false);
  const [bookedSet, setBookedSet] = useState(new Set());
  const t = window.I18N[lang];

  useEffect(() => {
    fetch('/api/booked-dates')
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then((d) => setBookedSet(new Set(d.dates)))
      .catch(() => {}); // on failure, fall back to empty set
  }, []);

  useEffect(() => {
    const onScroll = () => {
      setNavScrolled(window.scrollY > 30);
      setNavTransparent(window.scrollY < window.innerHeight - 80);
    };
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Fade-up observer
  useEffect(() => {
    const els = document.querySelectorAll('.fade-up');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [lang]);

  const onCalSelect = (key) => {
    if (!range.from || (range.from && range.to)) {
      setRange({ from: key, to: null });
    } else if (key < range.from) {
      setRange({ from: key, to: null });
    } else if (key === range.from) {
      setRange({ from: null, to: null });
    } else {
      // ensure no booked dates in between
      const start = new Date(range.from);
      const end = new Date(key);
      let conflict = false;
      const cur = new Date(start);
      cur.setDate(cur.getDate() + 1);
      while (cur < end) {
        if (bookedSet.has(cur.toISOString().slice(0,10))) { conflict = true; break; }
        cur.setDate(cur.getDate() + 1);
      }
      if (conflict) { setRange({ from: key, to: null }); }
      else setRange({ from: range.from, to: key });
    }
  };

  const nights = useMemo(() => {
    if (!range.from || !range.to) return 0;
    return Math.round((new Date(range.to) - new Date(range.from)) / 86400000);
  }, [range]);

  // Pricing: weekday=175, weekend (Fri/Sat night) = 225
  const accomTotal = useMemo(() => {
    if (!nights) return 0;
    let total = 0;
    const start = new Date(range.from);
    for (let i = 0; i < nights; i++) {
      const d = new Date(start); d.setDate(d.getDate() + i);
      const dow = d.getDay(); // 5=Fri, 6=Sat
      total += (dow === 5 || dow === 6) ? 225 : 175;
    }
    return total;
  }, [range, nights]);

  const fmtDate = (s) => {
    if (!s) return '—';
    const d = new Date(s);
    return d.toLocaleDateString(lang === 'ru' ? 'ru-RU' : (lang === 'en' ? 'en-GB' : 'et-EE'), { day: 'numeric', month: 'short' });
  };

  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'smooth' });
  };

  return (
    <>
      {/* NAV */}
      <nav className={`nav ${navScrolled ? 'scrolled' : ''} ${navTransparent ? 'transparent' : ''}`}>
        <div className="nav-inner">
          <div className="nav-links">
            <a href="#top" className="nav-brand" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}>
              <img src="assets/logo.png" alt="Päikeseraja" />
            </a>
            <a className="nav-link" onClick={() => scrollTo('about')}>{t.nav.about}</a>
            <a className="nav-link" onClick={() => scrollTo('gallery')}>{t.nav.gallery}</a>
            <a className="nav-link" onClick={() => scrollTo('amenities')}>{t.nav.amenities}</a>
            <a className="nav-link" onClick={() => scrollTo('booking')}>{t.nav.booking}</a>
            <a className="nav-link" onClick={() => scrollTo('contact')}>{t.nav.contact}</a>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <div className="lang-switch">
              {['et','en','ru'].map((L, i) => (
                <React.Fragment key={L}>
                  {i > 0 && <span className="lang-divider"></span>}
                  <button className={lang === L ? 'active' : ''} onClick={() => setLang(L)}>{L.toUpperCase()}</button>
                </React.Fragment>
              ))}
            </div>
            <button className="nav-cta" onClick={() => scrollTo('booking')}>{t.nav.bookNow}</button>
          </div>
        </div>
      </nav>

      {/* HERO */}
      <section className="hero" id="top" style={{ padding: 0 }}>
        <div className="hero-img"></div>
        <div className="hero-veil"></div>
        <div className="hero-inner">
          <div className="hero-eyebrow">{t.hero.eyebrow}</div>
          <h1>
            {t.hero.title.map((line, i) => (
              <React.Fragment key={i}>
                {line.includes(t.hero.titleEm) ? line.split(t.hero.titleEm).map((p, j) => (
                  <React.Fragment key={j}>{p}{j === 0 && <em>{t.hero.titleEm}</em>}</React.Fragment>
                )) : line}
                {i < t.hero.title.length - 1 && <br />}
              </React.Fragment>
            ))}
          </h1>
          <p className="lede">{t.hero.lede}</p>
          <div className="hero-actions">
            <button className="btn-primary" onClick={() => scrollTo('booking')}>
              {t.hero.cta1}
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 12 H19 M13 6 L19 12 L13 18" /></svg>
            </button>
            <button className="btn-ghost" onClick={() => scrollTo('gallery')}>{t.hero.cta2}</button>
          </div>
        </div>
        <div className="hero-scroll">
          <span>{t.hero.scroll}</span>
          <div className="hero-scroll-line"></div>
        </div>
      </section>

      {/* INTRO */}
      <section className="intro" id="about" data-screen-label="about">
        <div className="container">
          <div className="intro-grid">
            <div className="intro-text fade-up">
              <div className="eyebrow">{t.intro.eyebrow}</div>
              <h2 className="serif">
                {t.intro.title.map((w, i) => (
                  <React.Fragment key={i}>
                    {w === t.intro.titleEm ? <em>{w}</em> : w}{' '}
                  </React.Fragment>
                ))}
              </h2>
              <p>{t.intro.p1}</p>
              <p>{t.intro.p2}</p>
              <div className="intro-stats">
                {t.intro.stats.map((s, i) => (
                  <div key={i}>
                    <div className="num">{s.n}<em>+</em></div>
                    <div className="label">{s.label}</div>
                  </div>
                ))}
              </div>
            </div>
            <div className="intro-image fade-up">
              <img src="assets/guesthouse.jpg" alt="Peamaja" />
              <div className="intro-image-tag">{t.intro.tag}</div>
            </div>
          </div>
        </div>
      </section>

      {/* GALLERY */}
      <section className="gallery" id="gallery" data-screen-label="gallery">
        <div className="container">
          <div className="section-head fade-up">
            <div>
              <div className="eyebrow">{t.gallery.eyebrow}</div>
              <h2 className="serif">{t.gallery.title[0]} <em>{t.gallery.titleEm}</em>{t.gallery.title[1] && t.gallery.title[1].replace(t.gallery.titleEm, '')}</h2>
            </div>
            <p>{t.gallery.sub}</p>
          </div>
          <div className="mosaic fade-up">
            <figure className="m1"><img src="assets/drone.jpg" alt="" /><figcaption>{t.gallery.caps.drone}</figcaption></figure>
            <figure className="m2"><img src="assets/guesthouse.jpg" alt="" /><figcaption>{t.gallery.caps.guest}</figcaption></figure>
            <figure className="m3"><img src="assets/sauna.jpg" alt="" /><figcaption>{t.gallery.caps.sauna}</figcaption></figure>
            <figure className="m4"><img src="assets/main_room.jpg" alt="" /><figcaption>{t.gallery.caps.room}</figcaption></figure>
            <figure className="m5"><img src="assets/sauna_inside.jpg" alt="" /><figcaption>{t.gallery.caps.sauna_in}</figcaption></figure>
            <figure className="m6"><img src="assets/barrel_sauna.jpg" alt="" /><figcaption>{t.gallery.caps.barrel}</figcaption></figure>
            <figure className="m7"><img src="assets/bedroom1.jpg" alt="" /><figcaption>{t.gallery.caps.bed1}</figcaption></figure>
            <figure className="m8"><img src="assets/bedroom2.jpg" alt="" /><figcaption>{t.gallery.caps.bed2}</figcaption></figure>
          </div>
        </div>
      </section>

      {/* AMENITIES */}
      <section className="amenities" id="amenities" data-screen-label="amenities">
        <div className="container">
          <div className="section-head fade-up">
            <div>
              <div className="eyebrow">{t.amenities.eyebrow}</div>
              <h2 className="serif">{t.amenities.title[0]} <em>{t.amenities.titleEm}</em>{t.amenities.title.slice(1).join(' ').replace(t.amenities.titleEm, '')}</h2>
            </div>
            <p>{t.amenities.sub}</p>
          </div>
          <div className="amen-grid fade-up">
            {t.amenities.items.map((a, i) => {
              const icons = ['sauna','barrel','bed','pond','fire','kitchen','ball','trail','terrace','car','wifi','privacy'];
              return (
                <div className="amen" key={i}>
                  <div className="amen-icon"><Icon name={icons[i]} /></div>
                  <h4>{a.t}</h4>
                  <p>{a.d}</p>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* PRICING */}
      <section className="pricing" id="pricing" data-screen-label="pricing">
        <div className="container">
          <div className="section-head fade-up">
            <div>
              <div className="eyebrow">{t.pricing.eyebrow}</div>
              <h2 className="serif">{t.pricing.title[0]} <em>{t.pricing.titleEm}</em></h2>
            </div>
            <p>{t.pricing.sub}</p>
          </div>
          <div className="price-card fade-up">
            <div className="price-rows">
              {t.pricing.rows.map((r, i) => (
                <div className="price-row" key={i}>
                  <div className="label">{r.l}<small>{r.s}</small></div>
                  <div className="amount">{r.a === '—' ? <em>—</em> : <>{r.a}<span style={{ fontSize: 14, color: 'var(--ink-soft)', fontFamily: 'var(--sans)', marginLeft: 6 }}>{r.u}</span></>}</div>
                </div>
              ))}
            </div>
            <div className="price-aside">
              <div>
                <h4>{t.pricing.asideTitle}</h4>
                <p>{t.pricing.asideText}</p>
              </div>
              <div className="deposit">
                <strong>{t.pricing.depositTitle} · 50 €</strong>
                {t.pricing.depositText}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* BOOKING / CALENDAR */}
      <section className="booking" id="booking" data-screen-label="booking">
        <div className="container">
          <div className="section-head fade-up">
            <div>
              <div className="eyebrow">{t.booking.eyebrow}</div>
              <h2 className="serif">{t.booking.title[0]} <em>{t.booking.titleEm}</em></h2>
            </div>
            <p>{t.booking.sub}</p>
          </div>
          <div className="cal-wrap">
            <div className="fade-up">
              <Calendar t={t} selected={range} onSelect={onCalSelect} bookedSet={bookedSet} />
            </div>
            <div className="fade-up">
              <div className="book-side">
                <div className="eyebrow">{t.booking.sideEyebrow}</div>
                <h3>
                  {nights ? <>{nights} {t.booking.sideNights}</> : t.booking.sidePick}
                </h3>
                <p className="sub">{t.booking.sidePeople}</p>
                <div className="book-summary">
                  <div className="row"><span className="k">{t.form.datesFrom}</span><span className="v">{fmtDate(range.from)}</span></div>
                  <div className="row"><span className="k">{t.form.datesTo}</span><span className="v">{fmtDate(range.to)}</span></div>
                  <div className="row"><span className="k">{t.booking.sideAccom}</span><span className="v">{accomTotal ? `${accomTotal} €` : '—'}</span></div>
                  <div className="row total"><span>{t.booking.sideTotal}</span><span className="v">{accomTotal ? `${accomTotal} €` : '—'}</span></div>
                </div>
                {/* Booking flow disabled until payment integration is wired up. */}
                <div style={{ marginTop: 18, padding: '16px 18px', background: 'rgba(143,169,180,0.08)', borderRadius: 12, fontSize: 14, lineHeight: 1.55 }}>
                  <div style={{ marginBottom: 8 }}>{t.booking.sideUnavailable}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontWeight: 500 }}>
                    <a href="tel:+37253423106">+372 5342 3106</a>
                    <a href="mailto:taavikolk@hotmail.com">taavikolk@hotmail.com</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* LOCATION */}
      <section className="location" id="location" data-screen-label="location">
        <div className="container">
          <div className="loc-grid">
            <div className="loc-text fade-up">
              <div className="eyebrow">{t.location.eyebrow}</div>
              <h2 className="serif">{t.location.title.map((w, i) => (
                <React.Fragment key={i}>{w === t.location.titleEm ? <em>{w}</em> : w}{' '}</React.Fragment>
              ))}</h2>
              <p>{t.location.p1}</p>
              <p>{t.location.p2}</p>
              <div className="eyebrow" style={{ marginTop: 28, marginBottom: 4 }}>{t.location.nearbyTitle}</div>
              <ul className="nearby">
                {t.location.nearby.map((n, i) => (
                  <li key={i}><span className="n-name">{n.n}</span><span className="n-dist">{n.d}</span></li>
                ))}
              </ul>
            </div>
            <div className="loc-map fade-up" aria-label="map">
              <svg viewBox="0 0 400 400" preserveAspectRatio="none">
                <defs>
                  <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                    <path d="M40 0 H0 V40" fill="none" stroke="rgba(42,42,40,0.06)" strokeWidth="0.5" />
                  </pattern>
                </defs>
                <rect width="400" height="400" fill="url(#grid)" />
                <path d="M20 250 Q100 200 180 240 T380 220" stroke="rgba(143,169,180,0.6)" strokeWidth="2" fill="none" />
                <path d="M40 320 Q120 280 200 310 T360 290" stroke="rgba(143,169,180,0.5)" strokeWidth="1.5" fill="none" />
                <path d="M30 80 Q150 110 250 90 T390 120" stroke="rgba(125,140,124,0.5)" strokeWidth="2" fill="none" />
                <circle cx="80" cy="160" r="20" fill="rgba(125,140,124,0.18)" />
                <circle cx="320" cy="120" r="32" fill="rgba(125,140,124,0.18)" />
                <circle cx="290" cy="320" r="24" fill="rgba(125,140,124,0.18)" />
                <text x="50" y="380" fontSize="9" fill="rgba(42,42,40,0.4)" fontFamily="ui-monospace">Otepää</text>
                <text x="280" y="60" fontSize="9" fill="rgba(42,42,40,0.4)" fontFamily="ui-monospace">Tartu →</text>
                <text x="290" y="380" fontSize="9" fill="rgba(42,42,40,0.4)" fontFamily="ui-monospace">Võru</text>
              </svg>
              <div className="loc-pulse"></div>
              <div className="loc-pin"><span className="loc-pin-dot"></span></div>
              <div className="loc-coord">{t.location.coord}</div>
              <div className="loc-label">{t.location.label}</div>
            </div>
          </div>
        </div>
      </section>

      {/* REVIEWS */}
      <section className="reviews" id="reviews" data-screen-label="reviews">
        <div className="container">
          <div className="section-head fade-up">
            <div>
              <div className="eyebrow">{t.reviews.eyebrow}</div>
              <h2 className="serif">{t.reviews.title[0]} <em>{t.reviews.titleEm}</em></h2>
            </div>
          </div>
          <div className="review-grid">
            {t.reviews.items.map((r, i) => (
              <div className="review fade-up" key={i}>
                <div className="review-stars">
                  {[0,1,2,3,4].map((s) => (
                    <svg key={s} viewBox="0 0 24 24" fill="currentColor"><path d="M12 3 L14.5 9 L21 9.6 L16 13.8 L17.5 20 L12 16.7 L6.5 20 L8 13.8 L3 9.6 L9.5 9 Z" /></svg>
                  ))}
                </div>
                <div className="review-text">"{r.t}"</div>
                <div className="review-foot">
                  <div className="review-avatar">{r.i}</div>
                  <div className="review-meta">
                    <div className="name">{r.n}</div>
                    <div className="when">{r.w}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* HOUSE RULES */}
      <section className="rules" id="rules" data-screen-label="rules">
        <div className="container">
          <div className="section-head fade-up">
            <div>
              <div className="eyebrow">{t.rules.eyebrow}</div>
              <h2 className="serif">{t.rules.title[0]} <em>{t.rules.titleEm}</em></h2>
            </div>
          </div>
          <div className="rules-grid">
            {t.rules.items.map((r, i) => {
              const icons = ['clock','paw','smoke','star'];
              return (
                <div className="rule fade-up" key={i}>
                  <div className="rule-icon"><Icon name={icons[i]} /></div>
                  <div>
                    <h4>{r.t}</h4>
                    <p>{r.d}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* FOOTER */}
      <footer className="footer" id="contact" data-screen-label="contact">
        <div className="container">
          <div className="footer-grid">
            <div className="footer-brand">
              <img src="assets/logo.png" alt="Päikeseraja" />
              <p>{t.footer.tag}</p>
            </div>
            <div>
              <h5>{t.footer.explore}</h5>
              <ul>
                <li><a onClick={() => scrollTo('about')} style={{cursor:'pointer'}}>{t.nav.about}</a></li>
                <li><a onClick={() => scrollTo('gallery')} style={{cursor:'pointer'}}>{t.nav.gallery}</a></li>
                <li><a onClick={() => scrollTo('amenities')} style={{cursor:'pointer'}}>{t.nav.amenities}</a></li>
                <li><a onClick={() => scrollTo('booking')} style={{cursor:'pointer'}}>{t.nav.booking}</a></li>
              </ul>
            </div>
            <div>
              <h5>{t.footer.contact}</h5>
              <div className="footer-contact">
                <a href="tel:+37253423106">+372 5342 3106</a><br />
                <a href="mailto:taavikolk@hotmail.com">taavikolk@hotmail.com</a><br />
                <span style={{ color: 'rgba(255,255,255,0.6)', fontSize: 14 }}>Lõuna-Eesti</span>
              </div>
            </div>
            <div>
              <h5>{t.footer.platforms}</h5>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <a className="platform-chip" href="https://www.airbnb.com/rooms/911358168762608411" target="_blank" rel="noopener">Airbnb ↗</a>
                <a className="platform-chip" href="https://www.booking.com/hotel/ee/paikeseraja-talu.html" target="_blank" rel="noopener">Booking.com ↗</a>
              </div>
            </div>
          </div>
          <div className="footer-foot">
            <span>{t.footer.copy}</span>
            <span style={{ display: 'inline-flex', gap: 14 }}>
              <span style={{ color: 'rgba(255,255,255,0.4)', textTransform: 'uppercase', letterSpacing: '0.14em', fontSize: 11 }}>{t.footer.lang}:</span>
              {['et','en','ru'].map((L) => (
                <button key={L} onClick={() => setLang(L)} style={{ color: lang === L ? 'var(--gold-soft)' : 'rgba(255,255,255,0.6)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.14em', fontWeight: 600 }}>{L}</button>
              ))}
            </span>
          </div>
        </div>
      </footer>

      {modal && (
        <BookingModal
          t={t}
          lang={lang}
          range={range}
          nights={nights}
          accomTotal={accomTotal}
          onClose={() => setModal(false)}
        />
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
