/* global React, CONTENT */
const { useState, useEffect, useRef } = React;

// ============= EXTERNAL LINKS =============
const URL_DISTRIBUTOR = 'https://enrollment.unicity.com/c/POLSKI';
const URL_SHOP = 'https://unicity.link/ad1e21faba';
const URL_CALL = 'https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ0YH-YrMm8ViaATKiQ_LglFrD1AGpDCkxSofrMYPECks6qxHOPE70QCtOJduxlTT-judrBppnzq';
const extProps = { target: '_blank', rel: 'noopener noreferrer' };

// ============= ICONS (brand style: circular line icons) =============
function BIcon({ name, size = 56, color }) {
  const paths = {
    flask: <><path d="M10 4 L14 4 M12 4 L12 10 L8 18 L16 18 L12 10" stroke="currentColor" strokeWidth="1.25" fill="none" strokeLinecap="round" strokeLinejoin="round"/><circle cx="10" cy="15" r="0.8" fill="currentColor"/><circle cx="13" cy="16" r="0.6" fill="currentColor"/></>,
    globe: <><circle cx="12" cy="12" r="8" stroke="currentColor" strokeWidth="1.25" fill="none"/><ellipse cx="12" cy="12" rx="3" ry="8" stroke="currentColor" strokeWidth="1.25" fill="none"/><path d="M4 12 L20 12" stroke="currentColor" strokeWidth="1.25"/></>,
    shield: <path d="M12 3 L19 6 L19 12 C19 16 15 19 12 20 C9 19 5 16 5 12 L5 6 Z" stroke="currentColor" strokeWidth="1.25" fill="none" strokeLinejoin="round"/>,
    people: <><circle cx="9" cy="9" r="3" stroke="currentColor" strokeWidth="1.25" fill="none"/><circle cx="16" cy="10" r="2.5" stroke="currentColor" strokeWidth="1.25" fill="none"/><path d="M3 20 C3 16 6 14 9 14 C12 14 15 16 15 20" stroke="currentColor" strokeWidth="1.25" fill="none" strokeLinecap="round"/><path d="M14 20 C14 17 17 15 19 15 C20 15 21 15.5 21 16" stroke="currentColor" strokeWidth="1.25" fill="none" strokeLinecap="round"/></>,
  };
  return (
    <div className="bicon" style={{ width: size, height: size, color }}>
      <svg viewBox="0 0 24 24">{paths[name] || paths.flask}</svg>
    </div>
  );
}

// Original circular infinity-style mark (NOT Unicity logo)
function BrandMark({ size = 28, color }) {
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" style={{ color }}>
      <circle cx="20" cy="20" r="19" stroke="currentColor" strokeOpacity="0.85" strokeWidth="1.5" fill="none"/>
      <path d="M11 15 Q11 25 20 25 Q29 25 29 15" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round"/>
      <circle cx="20" cy="12" r="2" fill="currentColor"/>
    </svg>
  );
}

// ============= LANG BAR (floating) =============
function LangBar({ lang, setLang }) {
  return (
    <div className="langbar">
      <a href="#top" className="langbar-logo">
        <img src="assets/Unicity_hor_white.png" alt="Unicity" className="langbar-logo-img" />
      </a>
      <div className="lang-toggle langbar-toggle">
        <button className={lang === 'pl' ? 'active' : ''} onClick={() => setLang('pl')}>PL</button>
        <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
      </div>
    </div>
  );
}

// ============= NAV =============
function Nav({ lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);
  const t = CONTENT[lang];
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll); onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <a href="#top" className="nav-logo">
          <BrandMark />
          <span>UNICITY</span>
          <span className="nav-logo-region">POLSKA</span>
        </a>
        <div className="nav-links">
          <a href="#who" className="nav-link">{t.nav.who}</a>
          <a href="#problem" className="nav-link">{t.nav.problem}</a>
          <a href="#products" className="nav-link">{t.nav.products}</a>
          <a href="#ways" className="nav-link">{t.nav.ways}</a>
          <a href="#event" className="nav-link">{t.nav.event}</a>
          <a href="#faq" className="nav-link">{t.nav.faq}</a>
        </div>
        <div className="nav-right">
          <div className="lang-toggle">
            <button className={lang === 'pl' ? 'active' : ''} onClick={() => setLang('pl')}>PL</button>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <a href={URL_DISTRIBUTOR} {...extProps} className="nav-cta">{t.nav.cta}</a>
        </div>
      </div>
    </nav>
  );
}

// ============= HERO =============
function Hero({ lang }) {
  const t = CONTENT[lang].hero;
  return (
    <section className="hero" id="top">
      <div className="hero-bg">
        <div className="hero-photo" />
      </div>
      <div className="hero-content">
        <div className="hero-text">
          <div className="hero-eyebrow">
            <span className="hero-flag"></span>
            <span>{t.badge}</span>
          </div>
          <h1 className="display-xl">
            <span className="pl-line">{t.h1Main}</span>
            <span className="en-line">{t.h1Sub}</span>
          </h1>
          <p className="hero-lede">{t.lede}</p>
          <div className="hero-ctas">
            <a href={URL_SHOP} {...extProps} className="btn btn-coral btn-lg">{t.cta1} →</a>
            <a href={URL_DISTRIBUTOR} {...extProps} className="btn btn-outline-cream btn-lg">{t.cta2}</a>
          </div>
        </div>
        <div className="hero-visual">
          <div className="hero-visual-frame">
            <img src="assets/hero-morning.png" alt="" className="hero-visual-img" />
          </div>
        </div>
      </div>
      <div className="hero-stats">
        {t.stats.map((s, i) => (
          <div className="hero-stat-item" key={i}>
            <span className="hero-stat-num">{s.num}</span>
            <span className="hero-stat-label">{s.label}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============= WHO WE ARE =============
function Who({ lang }) {
  const t = CONTENT[lang].who;
  return (
    <section className="who section-pad" id="who">
      <div className="container">
        <div className="who-grid">
          <div className="who-copy reveal">
            <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
            <h2 className="display-md">{t.h2}<br/><span style={{ color: 'var(--ink-50)' }}>{t.h2Italic}</span></h2>
            <p>{t.p1}</p>
          </div>
          <div className="who-facts reveal delay-1">
            {t.facts.map((f, i) => (
              <div className="who-fact" key={i}>
                <BIcon name={f.icon} size={52} color="var(--coral-deep)" />
                <div>
                  <div className="who-fact-text" style={{ marginBottom: 4 }}>{f.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-50)', fontWeight: 400 }}>{f.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============= PROBLEM =============
function Problem({ lang }) {
  const t = CONTENT[lang].problem;
  return (
    <section className="problem section-pad" id="problem">
      <div className="container">
        <div className="problem-inner">
          <div className="problem-copy reveal">
            <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
            <h2 className="display-md" style={{ marginTop: 16 }}>{t.h2}<br/><span style={{ color: 'var(--coral)' }}>{t.h2Italic}</span></h2>
            <p>{t.p1}</p>
            <p className="emphasis">{t.p2}</p>
          </div>
          <div className="problem-stats reveal delay-1">
            {t.stats.map((s, i) => (
              <div className="problem-stat" key={i}>
                <div>
                  <div className="problem-stat-meta">{s.source}</div>
                </div>
                <div>
                  <div className="problem-stat-num">{s.num}</div>
                  <div className="problem-stat-label" style={{ marginTop: 10 }}>{s.label}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============= PRODUCTS =============
function Products({ lang }) {
  const t = CONTENT[lang].products;
  return (
    <section className="products section-pad" id="products">
      <div className="container">
        <div className="products-header reveal">
          <div>
            <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
            <h2 className="display-lg" style={{ marginTop: 14 }}>{t.h2}<br/><span style={{ color: 'var(--ink-50)' }}>{t.h2Italic}</span></h2>
          </div>
          <p>{t.p}</p>
        </div>
        <div className="products-grid">
          <ProductCard data={t.unimate} image="assets/unimate.png" href={URL_SHOP} reveal="reveal" />
          <ProductCard data={t.balance} image="assets/balance.png" href={URL_SHOP} reveal="reveal delay-1" coral />
        </div>
      </div>
    </section>
  );
}

function ProductCard({ data, image, href, reveal, coral }) {
  return (
    <article className={`product-card ${coral ? 'product-card--coral' : ''} ${reveal}`}>
      <a
        href={href}
        {...extProps}
        className={`product-shot product-shot--link ${coral ? 'product-shot--coral' : ''}`}
        aria-label={`${data.name} — shop`}
      >
        <img src={image} alt={data.name} className="product-shot-img" />
      </a>
      <div className="product-body">
        <div className="product-header">
          <div className="product-name">{data.name}<sup>®</sup></div>
          <div className="product-when">{data.when}</div>
        </div>
        <p className="product-tag">{data.tag}</p>
        <ul className="product-list">
          {data.list.map((item, i) => (
            <li key={i}>
              <span className="product-list-num">0{i + 1}</span>
              <span>{item}</span>
            </li>
          ))}
        </ul>
        <div className="product-flavors">
          <span>{data.flavorsLabel}:</span>
          {data.flavors.map(f => <span className="flavor-chip" key={f}>{f}</span>)}
        </div>
      </div>
    </article>
  );
}

// ============= DAILY RHYTHM =============
function Rhythm({ lang }) {
  const t = CONTENT[lang].rhythm;
  const [active, setActive] = useState(0);
  const sectionRef = useRef(null);
  const timerRef = useRef(null);

  useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          if (!timerRef.current) {
            timerRef.current = setInterval(() => {
              setActive(a => (a + 1) % t.steps.length);
            }, 2600);
          }
        } else {
          if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; }
        }
      });
    }, { threshold: 0.3 });
    io.observe(section);
    return () => { io.disconnect(); if (timerRef.current) clearInterval(timerRef.current); };
  }, [t.steps.length]);

  const progressPct = (active / (t.steps.length - 1)) * 100;
  const certs = ['Halal', 'Kosher', 'Gluten Free', 'GMP Certified', 'LGC Informed Choice', 'Clean Label', '3rd Party Tested'];

  return (
    <section className="rhythm section-pad" id="rhythm" ref={sectionRef}>
      <div className="container">
        <div className="rhythm-header reveal">
          <div className="eyebrow">{t.eyebrow}</div>
          <h2 className="display-md">{t.h2}</h2>
          <p>{t.p}</p>
        </div>
        <div className="rhythm-timeline reveal delay-1">
          <div className="rhythm-track">
            <div className="rhythm-progress" style={{ width: `${progressPct}%` }}></div>
            <div className="rhythm-sun" style={{ left: `${progressPct}%` }}></div>
          </div>
          <div className="rhythm-steps">
            {t.steps.map((s, i) => (
              <div
                key={i}
                className={`rhythm-step ${active === i ? 'active' : ''}`}
                onMouseEnter={() => { if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } setActive(i); }}
              >
                <div className="rhythm-step-time">{s.time}</div>
                <div className="rhythm-step-title">{s.title}</div>
                <div className="rhythm-step-desc">{s.desc}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="rhythm-certs reveal delay-2">
          {certs.map(c => <span className="cert-chip" key={c}>{c}</span>)}
        </div>
      </div>
    </section>
  );
}

// ============= VIDEOS (Instagram embeds) =============
const YT_PLAYLIST_ID = 'PLGXYTCmhclCt59z6ohURiZ8JZN178IuIq';
const YT_FIRST_VIDEO = 'Dq-076yCRDE';

function VideoCard({ v, i }) {
  const [playing, setPlaying] = useState(false);
  // Each card opens the playlist, each starting at its own index
  const embedSrc = `https://www.youtube.com/embed/${YT_FIRST_VIDEO}?list=${YT_PLAYLIST_ID}&index=${i + 1}&autoplay=1&rel=0&modestbranding=1`;
  const thumbSrc = `https://i.ytimg.com/vi/${YT_FIRST_VIDEO}/hqdefault.jpg`;
  return (
    <div className={`video-card reveal delay-${Math.min(3, i)}`}>
      <div className="video-thumb">
        {playing ? (
          <iframe
            className="video-iframe"
            src={embedSrc}
            title={v.title}
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
          />
        ) : (
          <>
            <img className="video-thumb-img" src={thumbSrc} alt={v.title} loading="lazy" />
            <div className="video-thumb-overlay" />
            <button className="video-play" aria-label={`Play ${v.title}`} onClick={() => setPlaying(true)}>
              <svg viewBox="0 0 20 20"><path d="M5 3 L17 10 L5 17 Z"/></svg>
            </button>
          </>
        )}
      </div>
      <div className="video-num">EP · {v.num}</div>
      <div className="video-title">{v.title}</div>
    </div>
  );
}

function Videos({ lang }) {
  const t = CONTENT[lang].videos;
  return (
    <section className="videos section-pad" id="videos">
      <div className="container">
        <div className="videos-header reveal">
          <div>
            <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
            <h2 className="display-md">{t.h2}</h2>
          </div>
          <p>{t.p}</p>
        </div>
        <div className="videos-grid">
          {t.items.map((v, i) => (
            <VideoCard key={i} v={v} i={i} />
          ))}
        </div>
      </div>
    </section>
  );
}

// ============= WAYS =============
function Ways({ lang }) {
  const t = CONTENT[lang].ways;
  const [tab, setTab] = useState(0);
  return (
    <section className="ways section-pad" id="ways">
      <div className="container">
        <div className="ways-header reveal">
          <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
          <h2 className="display-md">{t.h2}</h2>
        </div>
        <div className="ways-tabs-wrap reveal delay-1">
          <div className="ways-tabs">
            {t.tabs.map((label, i) => (
              <button key={i} className={`ways-tab ${tab === i ? 'active' : ''}`} onClick={() => setTab(i)}>{label}</button>
            ))}
          </div>
        </div>
        <div className="ways-content reveal delay-2">
          <WaysPanel data={t.member} active={tab === 0} image="assets/ways-box.jpg" />
          <WaysPanel data={{ ...t.distributor, isDistributor: true }} active={tab === 1} image="assets/ways-porch.jpg" />
        </div>
      </div>
    </section>
  );
}
function WaysPanel({ data, active, image }) {
  return (
    <div className={`ways-panel ${active ? 'active' : ''}`}>
      <div className="ways-panel-head">
        <div className="eyebrow eyebrow--coral">{data.title}</div>
        <h3>{data.headline}</h3>
        <p>{data.desc}</p>
        <a href={data.isDistributor ? URL_DISTRIBUTOR : URL_SHOP} {...extProps} className="btn btn-primary">{data.cta} →</a>
      </div>
      <div>
        <div className="ways-panel-img">
          <img src={image} alt="" />
        </div>
        <ul className="ways-benefits">
          {data.benefits.map(([num, text], i) => (
            <li key={i}><span>{num}</span><span>{text}</span></li>
          ))}
        </ul>
      </div>
    </div>
  );
}

// ============= EVENT =============
function Event({ lang }) {
  const t = CONTENT[lang].event;
  return (
    <section className="event section-pad" id="event">
      <div className="event-bg-text">Nice</div>
      <div className="container">
        <div className="event-inner">
          <div className="reveal">
            <div className="eyebrow" style={{ color: 'var(--coral)' }}>{t.eyebrow}</div>
            <h2 className="display-md event-title" style={{ marginTop: 14 }}>{t.h2}<br/><span style={{ color: 'var(--coral)' }}>{t.h2Italic}</span></h2>
            <div className="event-meta-row">
              <div className="event-meta-item">
                <span className="event-meta-label">{t.where}</span>
                <span className="event-meta-value">{t.whereValue}</span>
              </div>
              <div className="event-meta-item">
                <span className="event-meta-label">{t.when}</span>
                <span className="event-meta-value">{t.whenValue}</span>
              </div>
            </div>
            <p className="event-desc">{t.desc}</p>
            <a href="#" className="btn btn-on-navy">{t.cta} →</a>
          </div>
          <div className="event-card reveal delay-1">
            <div className="event-card-label">Unicity Europe · Inaugural</div>
            <div className="event-card-year">2026</div>
            <div className="event-card-num">26</div>
            <div className="event-card-month">sep.</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============= TESTIMONIALS =============
function Testimonials({ lang }) {
  const t = CONTENT[lang].testimonials;
  return (
    <section className="testimonials section-pad" id="testimonials">
      <div className="container">
        <div className="testimonials-header reveal">
          <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
          <h2 className="display-md">{t.h2}</h2>
        </div>
        <div className="testimonials-grid">
          {t.items.map((item, i) => (
            <div className={`testimonial reveal delay-${Math.min(2, i)}`} key={i}>
              <div className="testimonial-stars">★★★★★</div>
              <div className="testimonial-quote">"{item.quote}"</div>
              <div className="testimonial-author">
                <div className="testimonial-avatar">{item.name.charAt(0)}</div>
                <div className="testimonial-who">
                  <span className="testimonial-name">{item.name}</span>
                  <span className="testimonial-loc">{item.loc}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============= FAQ =============
function FAQ({ lang }) {
  const t = CONTENT[lang].faq;
  const [open, setOpen] = useState(0);
  return (
    <section className="faq section-pad" id="faq">
      <div className="container">
        <div className="faq-inner">
          <aside className="faq-aside reveal">
            <div className="eyebrow eyebrow--coral">{t.eyebrow}</div>
            <h2 className="display-sm">{t.h2}</h2>
            <p>{t.p}</p>
          </aside>
          <div className="faq-list reveal delay-1">
            {t.items.map((item, i) => (
              <div className={`faq-item ${open === i ? 'open' : ''}`} key={i}>
                <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                  <span>{item.q}</span><span className="faq-icon"></span>
                </button>
                <div className="faq-a"><div className="faq-a-inner">{item.a}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============= FINAL =============
function Final({ lang }) {
  const t = CONTENT[lang].final;
  return (
    <section className="final section-pad" id="final">
      <div className="final-bg">
        <img src="assets/lifestyle-porch.jpg" alt="" className="final-bg-img" />
        <div className="final-bg-overlay" />
      </div>
      <div className="container">
        <div className="final-inner reveal">
          <div className="eyebrow">{t.eyebrow}</div>
          <h2 className="display-lg">{t.h2}</h2>
          <p>{t.p}</p>
          <div className="final-ctas">
            <a href={URL_SHOP} {...extProps} className="btn btn-on-coral btn-lg">{t.cta1} →</a>
            <a href={URL_DISTRIBUTOR} {...extProps} className="btn btn-outline-on-coral btn-lg">{t.cta2} →</a>
          </div>
          <div className="final-book reveal delay-1">
            <div className="final-book-label">{t.cta3Sub}</div>
            <a href={URL_CALL} {...extProps} className="final-book-cta">
              <span>{t.cta3}</span>
              <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============= FOOTER =============
function Footer({ lang }) {
  const t = CONTENT[lang].footer;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div className="footer-col">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, color: 'var(--cream)' }}>
              <img src="assets/Unicity_hor_white.png" alt="Unicity" style={{ height: 22, width: 'auto' }} />
              <span style={{ fontWeight: 500, letterSpacing: '0.02em', fontSize: 12, textTransform: 'uppercase', opacity: 0.7 }}>Polska</span>
            </div>
            <div style={{ fontSize: 12, letterSpacing: '0.05em', color: 'var(--coral)', marginBottom: 16, fontWeight: 500, fontStyle: 'italic' }}>{t.tagline}</div>
            <p style={{ maxWidth: '34ch', lineHeight: 1.55 }}>{t.about}</p>
            <a href="https://instagram.com/unicityinternational" target="_blank" rel="noopener" className="footer-ig">
              <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5">
                <rect x="3" y="3" width="18" height="18" rx="5"/>
                <circle cx="12" cy="12" r="4"/>
                <circle cx="17.5" cy="6.5" r="0.75" fill="currentColor"/>
              </svg>
              <span>{t.instagramHandle}</span>
            </a>
          </div>
          <div className="footer-col"><h4>{t.col1Head}</h4><ul>{t.col1.map(i => <li key={i}><a href="#">{i}</a></li>)}</ul></div>
          <div className="footer-col"><h4>{t.col2Head}</h4><ul>{t.col2.map(i => <li key={i}><a href="#">{i}</a></li>)}</ul></div>
          <div className="footer-col"><h4>{t.col3Head}</h4><ul>{t.col3.map(i => <li key={i}><a href="#">{i}</a></li>)}</ul></div>
        </div>
        <div className="footer-disclaimer">{t.disclaimer}</div>
        <div className="footer-bottom">
          <div>{t.copyright}</div>
          <div>Warszawa · Kraków · Gdańsk</div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, LangBar, Hero, Who, Problem, Products, Rhythm, Videos, Ways, Event, Testimonials, FAQ, Final, Footer
});
