// ============================================================
// Main App — powerbi.ge
// ============================================================

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

// ---- Icons (Heroicons-inspired, custom-drawn) ----
const Icon = ({ name, size = 20, stroke = 1.6, style }) => {
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round', style };
  const paths = {
    chart: <><path d="M3 3v18h18" /><path d="M7 14l3-3 3 3 5-5" /></>,
    layers: <><path d="M12 2L2 7l10 5 10-5-10-5z" /><path d="M2 17l10 5 10-5" /><path d="M2 12l10 5 10-5" /></>,
    flow: <><circle cx="6" cy="6" r="2.5" /><circle cx="18" cy="6" r="2.5" /><circle cx="12" cy="18" r="2.5" /><path d="M8 7l8 0" /><path d="M7 8l4 8" /><path d="M17 8l-4 8" /></>,
    migrate: <><path d="M4 7h11" /><path d="M11 3l4 4-4 4" /><path d="M20 17H9" /><path d="M13 21l-4-4 4-4" /></>,
    plug: <><path d="M9 7V2" /><path d="M15 7V2" /><path d="M7 13a5 5 0 0 0 10 0V7H7v6z" /><path d="M12 18v4" /></>,
    audit: <><circle cx="11" cy="11" r="7" /><path d="M16 16l5 5" /><path d="M8 11h6" /><path d="M11 8v6" /></>,
    sparkles: <><path d="M12 2l2 6 6 2-6 2-2 6-2-6-6-2 6-2 2-6z" /><path d="M19 14l1 3 3 1-3 1-1 3-1-3-3-1 3-1 1-3z" /></>,
    location: <><path d="M12 21s-7-7.5-7-12a7 7 0 1114 0c0 4.5-7 12-7 12z" /><circle cx="12" cy="9" r="2.5" /></>,
    mail: <><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 7l9 6 9-6" /></>,
    phone: <path d="M5 4h4l2 5-3 2a12 12 0 005 5l2-3 5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z" />,
    clock: <><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 3" /></>,
    arrow: <><path d="M5 12h14" /><path d="M13 6l6 6-6 6" /></>,
    arrowUp: <><path d="M12 19V5" /><path d="M6 11l6-6 6 6" /></>,
    sun: <><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" /></>,
    moon: <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />,
    check: <path d="M5 12l4 4L19 7" />,
    whatsapp: <><path d="M3 21l1.65-3.8a9 9 0 113.4 3.36L3 21z" /><path d="M9 10c.5 1.5 1.5 2.5 3 3" /></>,
    linkedin: <><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M8 11v5M8 8.01v.01M12 16v-3a2 2 0 014 0v3M12 11v5" /></>,
    facebook: <><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M14 9h-1a2 2 0 00-2 2v3M9 12h5" /></>,
    youtube: <><rect x="3" y="6" width="18" height="12" rx="3" /><path d="M11 9.5l4 2.5-4 2.5z" /></>,
    bot: <><rect x="4" y="8" width="16" height="11" rx="3" /><path d="M12 8V4" /><circle cx="12" cy="3" r="1.2" /><path d="M9 13h.01M15 13h.01" /><path d="M9.5 16.5h5" /><path d="M2 12v3M22 12v3" /></>,
    x: <><path d="M6 6l12 12M18 6L6 18" /></>,
    minus: <path d="M5 12h14" />,
    chevronDown: <path d="M6 9l6 6 6-6" />
  };
  return <svg {...props}>{paths[name]}</svg>;
};

// ---- Animated counter ----
const Counter = ({ to, suffix = '' }) => {
  const [value, setValue] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        const start = performance.now();
        const dur = 1400;
        const tick = (now) => {
          const t = Math.min(1, (now - start) / dur);
          const eased = 1 - Math.pow(1 - t, 3);
          setValue(Math.round(to * eased));
          if (t < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
        obs.disconnect();
      }
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [to]);
  return <span ref={ref} className="mono">{value}<span className="stat-num-suffix">{suffix}</span></span>;
};

// ---- Navbar ----
const Navbar = ({ t, lang, setLang, theme, setTheme, activeSection, route }) =>
<header className="navbar">
    <div className="nav-inner">
      <a href="#home" className="logo">
        <span className="logo-mark">PB</span>
        <span style={{ fontFamily: "Ubuntu" }}>powerbi<span style={{ color: 'var(--accent)' }}>.ge</span></span>
      </a>
      <nav className="nav-links">
        {['home', 'services', 'courses', 'gallery', 'blog', 'contact'].map((id) => {
        const isPage = id === 'courses' || id === 'blog' || id === 'gallery' || id === 'reports';
        const active = isPage ? route === id : route === 'home' && activeSection === id;
        return (
          <a key={id} href={isPage ? `#/${id}` : `#${id}`} className={`nav-link ${active ? 'active' : ''}`} style={{ fontFamily: "\"BPG Mrgvlovani\"" }}>{t.nav[id]}</a>);
      })}
      </nav>
      <div className="nav-spacer" />
      <div className="lang-toggle">
        <button className={`lang-btn ${lang === 'en' ? 'active' : ''}`} onClick={() => setLang('en')}>EN</button>
        <button className={`lang-btn ${lang === 'ge' ? 'active' : ''}`} onClick={() => setLang('ge')}>ქარ</button>
      </div>
      <button className="theme-toggle-btn" onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')} title="Toggle theme">
        <Icon name={theme === 'light' ? 'moon' : 'sun'} size={16} />
      </button>
    </div>
  </header>;


// ---- Hero visual: rotates carousel images, falls back to static PNG ----
const HeroVisual = ({ t }) => {
  const slides = (t.hero && t.hero.carousel && Array.isArray(t.hero.carousel.items))
    ? t.hero.carousel.items.map((x) => x && x.image).filter(Boolean)
    : [];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (slides.length < 2) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % slides.length), 4000);
    return () => clearInterval(id);
  }, [slides.length]);

  if (slides.length === 0) {
    return <div className="hero-visual-img"><img src="Data report-pana.png" alt="Data Analytics Illustration" /></div>;
  }
  return (
    <div className="hero-visual-img hero-carousel">
      {slides.map((src, i) =>
        <img key={i} src={src} alt="" className={i === idx ? 'hero-slide on' : 'hero-slide'} />
      )}
    </div>
  );
};

// ---- Hero ----
const Hero = ({ t, lang }) =>
<section id="home" className="hero" style={{ fontFamily: "\"Noto Sans Georgian\"" }}>
    <div className="grid-bg" />
    <div className="container">
      <div className="hero-grid" style={{ fontFamily: "\"Noto Sans Georgian\"" }}>
        <div className="hero-content">
          <span className="eyebrow">{t.hero.eyebrow}</span>
          <h1 className="hero-headline" style={{ fontFamily: "\"Noto Sans Georgian\"", fontSize: "40px" }}>
            {t.hero.headline[0]}{' '}
            <em style={{ fontFamily: "Menlo" }}>{t.hero.headline[1]}</em>
            {t.hero.headline[2]}
          </h1>
          <p className="hero-sub">{t.hero.sub}</p>
          <div className="hero-meta mono" style={{ fontSize: "14px" }}>
            {t.hero.meta.map((m, i) =>
          <React.Fragment key={i}>
                {i > 0 && <span className="hero-meta-dot" />}
                <span style={{ fontFamily: "Raleway" }}>{m}</span>
              </React.Fragment>
          )}
          </div>
          <div className="hero-cta">
            <a href="#services" className="btn btn-primary btn-lg">{t.hero.ctaPrimary} <Icon name="arrow" size={16} /></a>
            <a href="#/gallery" className="btn btn-secondary btn-lg">{t.hero.ctaSecondary}</a>
          </div>
          <div className="hero-stats">
            {t.hero.stats.map((s, i) =>
          <div key={i} className="stat">
                <div className="stat-num"><Counter to={s.num} suffix={s.suffix} /></div>
                <div className="stat-label">{s.label}</div>
              </div>
          )}
          </div>
        </div>
        <HeroVisual t={t} />
      </div>
    </div>
  </section>;


// ---- Services ----
const SERVICE_ICONS = ['chart', 'layers', 'flow', 'bot', 'plug', 'audit', 'sparkles', 'migrate'];
const Services = ({ t }) =>
<section id="services">
    <div className="container">
      <span className="eyebrow">{t.services.eyebrow}</span>
      <h2 className="section-title" style={{ width: "500px", fontSize: "25px", fontFamily: "\"Noto Sans Georgian\"" }}>{t.services.title}</h2>
      <p className="section-subtitle">{t.services.subtitle}</p>
      <div className="services-grid">
        {t.services.items.map((s, i) =>
      <div key={i} className="service-card">
            <div className="service-icon"><Icon name={SERVICE_ICONS[i]} size={32} /></div>
            <h3 className="service-title">{s.title}</h3>
            <p className="service-desc">{s.desc}</p>
            <div className="service-tags">
              {s.tags.map((tag, j) => <span key={j} className="service-tag">{tag}</span>)}
            </div>
            <span className="service-arrow"><Icon name="arrow" size={18} /></span>
          </div>
      )}
        <a href="#/reports" className="service-card service-card-cta">
          <div className="service-icon"><Icon name="chart" size={32} /></div>
          <h3 className="service-title">{(t.reports && t.reports.cardTitle) || 'Live Reports'}</h3>
          <p className="service-desc">{(t.reports && t.reports.cardDesc) || ''}</p>
          <span className="service-arrow"><Icon name="arrow" size={18} /></span>
        </a>
      </div>
    </div>
  </section>;


// ---- Client logo carousel ----
const clientInitials = (name) => (name || '').split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase();

const ClientCarousel = ({ data }) => {
  if (!data || !data.items || !data.items.length) return null;
  const items = data.items;
  // Build one set wide enough to span the viewport, then render it twice for a seamless -50% loop
  const fill = items.length < 5 ? Math.ceil(8 / items.length) : 1;
  const oneSet = [];
  for (let r = 0; r < fill; r++) oneSet.push(...items);
  const duration = Math.max(20, oneSet.length * 4.5);
  return (
    <div className="client-carousel">
      {data.heading && <div className="client-carousel-heading mono">{data.heading}</div>}
      <div className="client-marquee">
        <div className="client-track" style={{ animationDuration: `${duration}s` }}>
          {oneSet.concat(oneSet).map((c, i) =>
          <div className="client-item" key={i} aria-hidden={i >= oneSet.length ? 'true' : undefined}>
              {c.logo ?
            <img className="client-logo" src={c.logo} alt={c.name} /> :
            <span className="client-monogram">{clientInitials(c.name)}</span>}
              <span className="client-name">{c.name}</span>
            </div>)}
        </div>
      </div>
    </div>);

};

// ---- Testimonials ----
const Testimonials = ({ t, lang }) => {
  const CS = window.ContentStore;
  const dynamicClients = CS.value(lang, 'testimonials.clients');
  const clientsData = dynamicClients || t.testimonials.clients;
  return (
<section className="testimonials">
    <div className="container">
      <span className="eyebrow">{t.testimonials.eyebrow}</span>
      <h2 className="section-title" style={{ fontFamily: "\"Noto Sans Georgian\"", fontSize: "40px" }}>{t.testimonials.title}</h2>
      <ClientCarousel data={clientsData} />
      <div className="testimonial-track">
        {t.testimonials.items.map((it, i) =>
      <div key={i} className="testimonial">
            <div className="testimonial-quote-mark">"</div>
            <p className="testimonial-text">{it.quote}</p>
            <div className="testimonial-author">
              <div className="avatar">{it.initials || clientInitials(it.name)}</div>
              <div>
                <div className="testimonial-name">{it.name}</div>
                <div className="testimonial-role">{it.role}</div>
              </div>
            </div>
          </div>
      )}
      </div>
    </div>
  </section>
  );
};

// ---- Courses ----
const CourseCard = ({ c, featured }) =>
<div className={`course-card ${featured ? 'featured' : ''}`}>
    {featured && <span className="course-badge" style={{ backgroundColor: "rgba(28, 107, 76, 0)" }}>{c.badge}</span>}
    <div className="course-header">
      <div>
        <div className="course-name" style={{ fontSize: "20px", textAlign: "left" }}>{c.name}</div>
        <div className="course-format mono" style={{ fontSize: "15px" }}>{c.format}</div>
      </div>
      <div className="course-price">
        <div className="price-num">{c.price}</div>
        <div className="price-currency">{c.currency}</div>
      </div>
    </div>
    <ul className="course-features">
      {c.features.map((f, i) =>
    <li key={i}><span className="check"><Icon name="check" size={16} /></span><span>{f}</span></li>
    )}
    </ul>
    <div className="course-topics">
      <div className="course-topics-label">Curriculum</div>
      <div className="course-topics-list">
        {c.topics.map((tp, i) => <span key={i} className="topic-pill">{tp}</span>)}
      </div>
    </div>
    <a href="#contact" className={`btn ${featured ? 'btn-primary' : 'btn-secondary'} btn-lg`} style={{ justifyContent: 'center' }}>
      {c.cta} <Icon name="arrow" size={16} />
    </a>
  </div>;


const Courses = ({ t }) =>
<section id="courses" style={{ fontSize: "35px" }}>
    <div className="container">
      <span className="eyebrow">{t.courses.eyebrow}</span>
      <h2 className="section-title" style={{ fontFamily: "\"Noto Sans Georgian\"", fontSize: "40px" }}>{t.courses.title}</h2>
      <p className="section-subtitle" style={{ fontSize: "20px" }}>{t.courses.subtitle}</p>
      <div className="courses-grid">
        <CourseCard c={t.courses.solo} featured />
        <CourseCard c={t.courses.group} />
      </div>
      <div className="syllabus-link-row">
        <a href="#/syllabus" className="syllabus-link mono">{t.courses.syllabusCta} <Icon name="arrow" size={16} /></a>
      </div>
      <p className="course-note">{t.courses.note}</p>
      <VideoCourseLibrary t={t} />
    </div>
  </section>;


// ---- Interactive demo dashboard ----
const InteractiveDashboard = ({ t }) => {
  const [period, setPeriod] = useState('Q1');
  const [segment, setSegment] = useState('All');
  const periods = ['Q1', 'Q2', 'Q3', 'Q4', 'YTD'];
  const segments = ['All', 'VIP', 'Regular', 'New'];

  const seed = period.length + segment.length;
  const random = (i) => (Math.sin(i * 9 + seed * 17) + 1) / 2;
  const revenue = period === 'YTD' ? '\u20be 11.2M' : period === 'Q1' ? '\u20be 2.84M' : period === 'Q2' ? '\u20be 3.12M' : period === 'Q3' ? '\u20be 2.98M' : '\u20be 2.26M';
  const orders = period === 'YTD' ? 42184 : period === 'Q1' ? 10482 : period === 'Q2' ? 11240 : period === 'Q3' ? 10812 : 9650;
  const segMult = segment === 'VIP' ? 0.34 : segment === 'Regular' ? 0.52 : segment === 'New' ? 0.14 : 1;

  const monthly = Array.from({ length: 12 }, (_, i) => 18 + Math.round(random(i) * 22));
  const byCat = Array.from({ length: 8 }, (_, i) => 40 + Math.round(random(i + 5) * 60));

  return (
    <div className="dash-embed">
      <div className="dash-embed-header">
        <div className="dash-embed-title">
          <Icon name="chart" size={18} />
          <span>{t.gallery.liveDemoTitle}</span>
          <span className="live-badge">LIVE</span>
        </div>
        <div className="dash-embed-controls">
          {periods.map((p) =>
          <button key={p} className={`filter-chip ${period === p ? 'active' : ''}`} onClick={() => setPeriod(p)}>{p}</button>
          )}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 6, padding: '10px 20px', borderBottom: '1px solid var(--line)', background: 'var(--bg-elev)', alignItems: 'center' }}>
        <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--ink-3)', marginRight: 6 }}>SEGMENT \u00b7</span>
        {segments.map((s) =>
        <button key={s} className={`filter-chip ${segment === s ? 'active' : ''}`} onClick={() => setSegment(s)}>{s}</button>
        )}
      </div>
      <div className="dash-embed-body">
        <div className="kpi-tile" style={{ gridColumn: 'span 3' }}>
          <div className="kpi-label">Revenue</div>
          <div className="kpi-value">{revenue}</div>
          <div className="kpi-delta up">\u2197 +{(8 + segMult * 4).toFixed(1)}% vs LY</div>
          <Spark data={monthly.map((v) => v * segMult)} color={COLORS.green} w={70} h={28} />
        </div>
        <div className="kpi-tile" style={{ gridColumn: 'span 3' }}>
          <div className="kpi-label">Orders</div>
          <div className="kpi-value mono">{Math.round(orders * segMult).toLocaleString()}</div>
          <div className="kpi-delta up">\u2197 +6.4%</div>
        </div>
        <div className="kpi-tile" style={{ gridColumn: 'span 3' }}>
          <div className="kpi-label">Avg Basket</div>
          <div className="kpi-value">\u20be {(180 + segMult * 50).toFixed(0)}</div>
          <div className="kpi-delta up">\u2197 +2.1%</div>
        </div>
        <div className="kpi-tile" style={{ gridColumn: 'span 3' }}>
          <div className="kpi-label">Conversion</div>
          <div className="kpi-value">{(3.2 + segMult * 0.8).toFixed(1)}%</div>
          <div className="kpi-delta down">\u2198 -0.3pp</div>
        </div>
        
        <div className="chart-tile" style={{ gridColumn: 'span 8' }}>
          <div className="chart-tile-title">
            <h4>Monthly Revenue \u00b7 {period} \u00b7 {segment} segment</h4>
            <span className="menu">\u22ef</span>
          </div>
          <div style={{ height: 160 }}>
            <LineChart series={[monthly.map((v) => v * segMult), monthly.map((v) => v * segMult * 0.85)]} w={400} h={160} colors={[COLORS.blue, COLORS.yellow]} />
          </div>
          <div style={{ display: 'flex', gap: 14, marginTop: 6, fontSize: 10, color: 'var(--ink-3)', fontFamily: 'JetBrains Mono, monospace' }}>
            <span><span style={{ display: 'inline-block', width: 10, height: 3, background: COLORS.blue, marginRight: 5, verticalAlign: 'middle' }}></span>Actual</span>
            <span><span style={{ display: 'inline-block', width: 10, height: 3, background: COLORS.yellow, marginRight: 5, verticalAlign: 'middle' }}></span>Forecast</span>
          </div>
        </div>
        <div className="chart-tile" style={{ gridColumn: 'span 4' }}>
          <div className="chart-tile-title">
            <h4>By region</h4>
            <span className="menu">\u22ef</span>
          </div>
          <div style={{ height: 160, display: 'grid', placeItems: 'center' }}>
            <Donut data={[42 + segMult * 4, 28, 18, 12]} size={120} colors={[COLORS.blue, COLORS.yellow, COLORS.blue3, COLORS.greenL]} />
          </div>
        </div>
        
        <div className="chart-tile" style={{ gridColumn: 'span 6' }}>
          <div className="chart-tile-title">
            <h4>Top categories</h4>
            <span className="menu">\u22ef</span>
          </div>
          <div style={{ height: 120 }}>
            <BarChart data={byCat} h={120} color={COLORS.blue} />
          </div>
        </div>
        <div className="chart-tile" style={{ gridColumn: 'span 6' }}>
          <div className="chart-tile-title">
            <h4>Daypart heatmap</h4>
            <span className="menu">\u22ef</span>
          </div>
          <div style={{ height: 120 }}>
            <Heatmap rows={6} cols={16} />
          </div>
        </div>
      </div>
    </div>);

};

// ---- Gallery ----
const Gallery = ({ t }) => {
  const [filter, setFilter] = useState(t.gallery.filters[0]);
  const filtered = filter === t.gallery.filters[0] ? t.gallery.items : t.gallery.items.filter((it) => it.tag === filter);

  return (
    <section id="gallery">
      <div className="container">
        <span className="eyebrow">{t.gallery.eyebrow}</span>
        <h2 className="section-title">{t.gallery.title}</h2>
        <p className="section-subtitle">{t.gallery.subtitle}</p>
        
        <InteractiveDashboard t={t} />
        
        <div className="gallery-filters">
          {t.gallery.filters.map((f) => {
            const count = f === t.gallery.filters[0] ? t.gallery.items.length : t.gallery.items.filter((it) => it.tag === f).length;
            return (
              <button key={f} className={`filter-btn ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>
                {f}<span className="filter-count">{count}</span>
              </button>);

          })}
        </div>
        <div className="gallery-grid">
          {filtered.map((it, i) => {
            const inner = <>
              <div className="gallery-thumb">
                {it.embed ?
                  <iframe className="gallery-embed" src={it.embed} title={it.title} frameBorder="0" loading="lazy" allowFullScreen /> :
                  <GalleryThumb kind={it.kind} />}
              </div>
              <div className="gallery-info">
                <div className="gallery-tag">{it.tag}</div>
                <div className="gallery-title">{it.title}</div>
                <div className="gallery-desc">{it.desc}</div>
              </div>
            </>;
            return it.url ?
              <a key={i} className="gallery-item gallery-item-link" href={it.url} target="_blank" rel="noopener noreferrer">{inner}</a> :
              <div key={i} className="gallery-item">{inner}</div>;
          })}
        </div>
      </div>
    </section>);

};

// ---- Reports page ----
const ReportsPage = ({ t }) => {
  const r = t.reports || {};
  const items = Array.isArray(r.items) ? r.items : [];
  return (
    <section id="reports">
      <div className="container">
        <span className="eyebrow">{r.eyebrow}</span>
        <h2 className="section-title">{r.title}</h2>
        <p className="section-subtitle">{r.subtitle}</p>
        {items.length === 0 ?
        <p className="reports-empty">{r.emptyText}</p> :
        <div className="reports-grid">
            {items.map((it, i) =>
          <div key={i} className="report-card">
                {it.embed ?
            <div className="report-embed">
                    <iframe src={it.embed} title={it.title || 'report'} frameBorder="0" allowFullScreen loading="lazy" />
                  </div> : null}
                <div className="report-info">
                  {it.title && <div className="report-title">{it.title}</div>}
                  {it.desc && <div className="report-desc">{it.desc}</div>}
                  {it.url && <a className="btn btn-secondary" href={it.url} target="_blank" rel="noopener noreferrer">{r.openLabel} <Icon name="arrow" size={15} /></a>}
                </div>
              </div>
          )}
          </div>}
      </div>
    </section>);

};

// ---- Blog post page ----
function BlogPostPage({ t, index, lang }) {
  const post = t.blog.items[index];
  useEffect(() => {window.scrollTo(0, 0);}, [index]);
  const backLabel = lang === 'ge' ? '\u10d1\u10da\u10dd\u10d2\u10d6\u10d4 \u10d3\u10d0\u10d1\u10e0\u10e3\u10dc\u10d4\u10d1\u10d0' : 'Back to blog';
  if (!post)
  return (
    <section className="post-page">
      <div className="post-wrap">
        <a href="#/blog" className="post-back mono"><Icon name="arrow" size={16} style={{ transform: 'rotate(180deg)' }} /> {backLabel}</a>
        <p className="bpm-no-content">404 — {lang === 'ge' ? '\u10de\u10dd\u10e1\u10e2\u10d8 \u10d5\u10d4\u10e0 \u10d8\u10de\u10dd\u10d5\u10dc\u10d0' : 'Post not found'}.</p>
      </div>
    </section>);

  return (
    <section className="post-page">
      <div className="post-wrap">
        <a href="#/blog" className="post-back mono"><Icon name="arrow" size={16} style={{ transform: 'rotate(180deg)' }} /> {backLabel}</a>
        <div className="bpm-meta mono">
          <span className="bpm-tag">{post.tag}</span>
          <span className="blog-card-dot" />
          <span>{post.date}</span>
          <span className="blog-card-dot" />
          <Icon name="clock" size={12} />
          <span>{post.readTime}</span>
        </div>
        <h1 className="bpm-title">{post.title}</h1>
        <p className="bpm-excerpt">{post.excerpt}</p>
        {post.cover && <div className="post-cover"><img src={post.cover} alt={post.title} /></div>}
        {post.content ?
        <div className="bpm-content">{post.content.split('\n').map((para, i) => para.trim() ? <p key={i}>{para}</p> : <br key={i} />)}</div> :
        <p className="bpm-no-content">{lang === 'ge' ? '\u10e1\u10e0\u10e3\u10da\u10d8 \u10e1\u10e2\u10d0\u10e2\u10d8\u10d0 \u10db\u10d0\u10da\u10d4!' : 'Full article coming soon.'}</p>}
        <div className="post-foot">
          <a href="#/blog" className="post-back mono"><Icon name="arrow" size={16} style={{ transform: 'rotate(180deg)' }} /> {backLabel}</a>
        </div>
      </div>
    </section>);

}

// ---- Syllabus page ----
function SyllabusPage({ t }) {
  const s = t.courses.syllabus;
  useEffect(() => {window.scrollTo(0, 0);}, []);
  return (
    <section className="post-page syllabus-page">
      <div className="syllabus-wrap">
        <div style={{ marginBottom: '30px' }}><a href="#/courses" className="post-back mono"><Icon name="arrow" size={16} style={{ transform: 'rotate(180deg)' }} /> {s.back}</a></div>
        <span className="eyebrow">{s.eyebrow}</span>
        <h1 className="syllabus-title">{s.title}</h1>
        <p className="syllabus-subtitle">{s.subtitle}</p>
        <ol className="syllabus-modules">
          {s.modules.map((m, i) =>
          <li key={i} className="syllabus-module">
            <div className="syllabus-module-head">
              <span className="syllabus-num mono">{String(i + 1).padStart(2, '0')}</span>
              <h2 className="syllabus-module-title">{m.title}</h2>
            </div>
            <ul className="syllabus-lessons">
              {m.lessons.map((ls, j) =>
              <li key={j}><span className="check"><Icon name="check" size={15} /></span><span>{ls}</span></li>)}
            </ul>
          </li>)}
        </ol>
        <div className="syllabus-foot">
          <a href="#contact" className="btn btn-primary btn-lg" style={{ justifyContent: 'center' }}>{t.courses.solo.cta} <Icon name="arrow" size={16} /></a>
        </div>
      </div>
    </section>);

}

// ---- Blog ----
function Blog({ t }) {
  const go = (i) => {window.location.hash = `#/blog/${i}`;};
  return (
    <section id="blog">
      <div className="container">
        <span className="eyebrow">{t.blog.eyebrow}</span>
        <h2 className="section-title">{t.blog.title}</h2>
        <p className="section-subtitle">{t.blog.subtitle}</p>
        <div className="blog-grid">
          {t.blog.items.map((post, i) =>
          <article key={i} className={`blog-card${post.cover ? ' blog-card--has-cover' : ''}`} onClick={() => go(i)} role="button" tabIndex={0} onKeyDown={(e) => e.key === 'Enter' && go(i)}>
              {post.cover && <div className="blog-card-cover"><img src={post.cover} alt={post.title} /></div>}
              <div className="blog-card-body">
                <div className="blog-card-meta mono">
                  <span className="blog-card-tag">{post.tag}</span>
                  <span className="blog-card-dot" />
                  <span>{post.date}</span>
                  <span className="blog-card-dot" />
                  <span>{post.readTime}</span>
                </div>
                <h3 className="blog-card-title">{post.title}</h3>
                <span className="blog-card-link mono">{t.blog.readMore} <Icon name="arrow" size={14} /></span>
              </div>
            </article>
          )}
        </div>
      </div>
    </section>);

}


// ---- Contact ----
const Contact = ({ t }) => {
  const [form, setForm] = useState({ name: '', email: '', phone: '', service: '', message: '' });
  const [sent, setSent] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (window.Submissions) window.Submissions.add(form);
    setSent(true);
    setForm({ name: '', email: '', phone: '', service: '', message: '' });
    setTimeout(() => setSent(false), 4000);
  };

  const update = (k, v) => setForm({ ...form, [k]: v });

  return (
    <section id="contact">
      <div className="container">
        <span className="eyebrow">{t.contact.eyebrow}</span>
        <h2 className="section-title" style={{ fontFamily: "\"Noto Sans Georgian\"", fontSize: "25px" }}>{t.contact.title}</h2>
        <p className="section-subtitle">{t.contact.subtitle}</p>
        <div className="contact-grid">
          <div className="contact-info-card">
            <div className="contact-row">
              <div className="contact-icon"><Icon name="location" size={18} /></div>
              <div>
                <div className="contact-label">{t.contact.info.location.label}</div>
                <div className="contact-value">{t.contact.info.location.value}</div>
              </div>
            </div>
            <div className="contact-row">
              <div className="contact-icon"><Icon name="mail" size={18} /></div>
              <div>
                <div className="contact-label">{t.contact.info.email.label}</div>
                <div className="contact-value">{t.contact.info.email.value}</div>
              </div>
            </div>
            <div className="contact-row">
              <div className="contact-icon"><Icon name="phone" size={18} /></div>
              <div>
                <div className="contact-label">{t.contact.info.phone.label}</div>
                <div className="contact-value">{t.contact.info.phone.value}</div>
              </div>
            </div>
            <div className="contact-row">
              <div className="contact-icon"><Icon name="clock" size={18} /></div>
              <div>
                <div className="contact-label">{t.contact.info.response.label}</div>
                <div className="contact-value">{t.contact.info.response.value}</div>
              </div>
            </div>
            <div className="social-row">
              {['linkedin', 'facebook', 'youtube'].map((s) =>
              <a key={s} className="social-btn" href="#"><Icon name={s} size={18} /></a>
              )}
            </div>
          </div>
          
          <form className="form-card" onSubmit={submit}>
            <div className="form-row">
              <div className="form-group">
                <label className="form-label">{t.contact.form.name}</label>
                <input className="form-input" type="text" required value={form.name} onChange={(e) => update('name', e.target.value)} placeholder="Nino Beridze" />
              </div>
              <div className="form-group">
                <label className="form-label">{t.contact.form.email}</label>
                <input className="form-input" type="email" required value={form.email} onChange={(e) => update('email', e.target.value)} placeholder="you@company.com" />
              </div>
            </div>
            <div className="form-row">
              <div className="form-group">
                <label className="form-label">{t.contact.form.phone}</label>
                <input className="form-input" type="tel" value={form.phone} onChange={(e) => update('phone', e.target.value)} placeholder="+995 ..." />
              </div>
              <div className="form-group">
                <label className="form-label">{t.contact.form.service}</label>
                <select className="form-select" value={form.service} onChange={(e) => update('service', e.target.value)}>
                  <option value="">{t.contact.form.servicePlaceholder}</option>
                  {t.contact.form.serviceOptions.map((o) => <option key={o} value={o}>{o}</option>)}
                </select>
              </div>
            </div>
            <div className="form-row" style={{ gridTemplateColumns: '1fr' }}>
              <div className="form-group full">
                <label className="form-label">{t.contact.form.message}</label>
                <textarea className="form-textarea" required value={form.message} onChange={(e) => update('message', e.target.value)} placeholder="What are you trying to measure or fix?" />
              </div>
            </div>
            <button type="submit" className="btn btn-primary btn-lg" style={{ width: '100%', justifyContent: 'center' }}>
              {sent ? t.contact.form.sent : t.contact.form.submit}
              {!sent && <Icon name="arrow" size={16} />}
            </button>
          </form>
        </div>
      </div>
    </section>);

};

// ---- Footer ----
const Footer = ({ t }) =>
<footer>
    <div className="footer-inner">
      <div>
        <div className="logo" style={{ color: 'white' }}>
          <span className="logo-mark">PB</span>
          <span style={{ color: 'white' }}>powerbi<span style={{ color: 'var(--pbi-yellow)' }}>.ge</span></span>
        </div>
        <p className="footer-tagline">{t.footer.tagline}</p>
      </div>
      <div className="footer-col">
        <h5>{t.footer.services}</h5>
        {t.services.items.slice(0, 5).map((s, i) => <a key={i} className="footer-link">{s.title}</a>)}
      </div>
      <div className="footer-col">
        <h5>{t.footer.navigate}</h5>
        {['home', 'services', 'courses', 'gallery', 'reports', 'blog', 'contact'].map((id) =>
      <a key={id} className="footer-link" href={id === 'courses' || id === 'blog' || id === 'gallery' || id === 'reports' ? `#/${id}` : `#${id}`}>{t.nav[id]}</a>
      )}
      </div>
      <div className="footer-col">
        <h5>{t.footer.legal}</h5>
        {t.footer.legalItems.map((l) => <a key={l} className="footer-link">{l}</a>)}
      </div>
    </div>
    <div className="footer-bottom">
      <span>{t.footer.copyright}</span>
      <span>{t.footer.tag}</span>
    </div>
  </footer>;


// ---- Chat widget ----
const ChatIcon = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" /></svg>;

const GREETING = 'გამარჯობა, დახმარება ხომ არ გნებავთ?';

function ChatWidget({ t }) {
  const isGe = t === window.ContentStore.get('ge');
  const [open, setOpen] = useState(false);
  const [name] = useState('');
  const [draft, setDraft] = useState('');
  const [messages, setMessages] = useState([{ id: 'greeting', content: GREETING, from: 'admin', ts: new Date().toISOString() }]);
  const [threadId, setThreadId] = useState(null);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState('');
  const bottomRef = useRef(null);
  const inputRef = useRef(null);
  const pollRef = useRef(null);
  const lastIdRef = useRef(null);
  const seenIds = useRef(new Set());

  // auto-open once per session
  useEffect(() => {
    if (sessionStorage.getItem('_pbi_chat_opened')) return;
    const t = setTimeout(() => {
      sessionStorage.setItem('_pbi_chat_opened', '1');
      setOpen(true);
    }, 2500);
    return () => clearTimeout(t);
  }, []);

  // auto-scroll to bottom
  useEffect(() => {bottomRef.current && bottomRef.current.scrollIntoView({ behavior: 'smooth' });}, [messages]);

  // focus input when opened
  useEffect(() => {if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 150);}, [open]);

  // start/stop polling — interval never restarts mid-session; lastIdRef updated via ref
  useEffect(() => {
    if (!open || !threadId) return;
    const poll = async () => {
      try {
        const url = `/api/chat-poll?threadId=${threadId}${lastIdRef.current ? `&after=${lastIdRef.current}` : ''}`;
        const data = await fetch(url).then((r) => r.json());
        if (data.messages && data.messages.length) {
          const fresh = data.messages.
          filter((m) => !seenIds.current.has(m.id)).
          map((m) => {seenIds.current.add(m.id);return { id: m.id, content: m.content, from: 'admin', ts: m.timestamp };});
          if (fresh.length) {
            lastIdRef.current = data.messages[data.messages.length - 1].id;
            setMessages((prev) => [...prev, ...fresh]);
          }
        }
      } catch (_) {}
    };
    pollRef.current = setInterval(poll, 2000);
    return () => clearInterval(pollRef.current);
  }, [open, threadId]);

  const send = async (e) => {
    e && e.preventDefault();
    const text = draft.trim();
    if (!text || sending) return;
    setSending(true);
    setError('');
    const visitorMsg = { id: 'v-' + Date.now(), content: text, from: 'visitor', ts: new Date().toISOString() };
    setMessages((prev) => [...prev, visitorMsg]);
    setDraft('');
    try {
      const body = { message: text, visitorName: name || (isGe ? 'ვიზიტორი' : 'Visitor') };
      if (threadId) body.threadId = threadId;
      const data = await fetch('/api/chat-send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      }).then((r) => r.json());
      if (data.threadId) setThreadId(data.threadId);
      if (data.messageId) {lastIdRef.current = data.messageId;seenIds.current.add(data.messageId);}
    } catch (_) {
      setError(isGe ? 'შეცდომა. სცადეთ თავიდან.' : 'Failed to send. Try again.');
    }
    setSending(false);
  };

  const onKey = (e) => {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault();send();}};

  const close = () => setOpen(false);

  return (
    <>
      {open &&
      <div className="chat-panel">
          <div className="chat-panel-head">
            <div className="chat-panel-title">
              <span className="chat-dot" />
              {isGe ? 'პირდაპირი ჩათი' : 'Live chat'}
            </div>
            <button className="chat-close" onClick={close} aria-label={isGe ? 'ჩაკეცვა' : 'Minimize'} title={isGe ? 'ჩაკეცვა' : 'Minimize'}><Icon name="minus" size={20} stroke={2.4} /></button>
          </div>
          <div className="chat-messages">
            {messages.map((m) =>
          <div key={m.id} className={`chat-bubble chat-bubble--${m.from}`}>
                <span>{m.content}</span>
              </div>
          )}
            {error && <p className="chat-error">{error}</p>}
            <div ref={bottomRef} />
          </div>
          <form className="chat-compose" onSubmit={send}>
            <textarea ref={inputRef} className="chat-input chat-compose-input" placeholder={isGe ? 'მოწერეთ...' : 'Type a message...'} value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={onKey} rows={2} />
            <button className="chat-send-btn" type="submit" disabled={sending || !draft.trim()} title="Send">
              <Icon name="arrow" size={18} />
            </button>
          </form>
        </div>
      }
      <button className={`float-btn float-chat ${open ? 'active' : ''}`} onClick={() => setOpen((o) => !o)} title={isGe ? 'ჩათი' : 'Chat'}>
        {open ? <Icon name="x" size={20} /> : <ChatIcon />}
      </button>
    </>);

}

// ---- Floating buttons ----
const Floating = ({ t }) => {
  const [topVisible, setTopVisible] = useState(false);
  useEffect(() => {
    const onScroll = () => setTopVisible(window.scrollY > 600);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div className="floating-stack">
      <button className={`float-btn float-back-top ${topVisible ? 'visible' : ''}`} onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} title="Back to top">
        <Icon name="arrowUp" size={20} />
      </button>
<ChatWidget t={t} />
    </div>);

};

// ---- Scroll progress ----
const ScrollProgress = () => {
  const ref = useRef();
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const pct = h.scrollTop / (h.scrollHeight - h.clientHeight) * 100;
      if (ref.current) ref.current.style.width = `${pct}%`;
    };
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div className="scroll-progress" ref={ref} />;
};

// ---- Tweaks ----
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "lang": "ge",
  "font": "noto"
} /*EDITMODE-END*/;

const FONT_OPTIONS = [
{ value: 'noto', label: 'Noto Sans Georgian (default)' },
{ value: 'noto-serif', label: 'Noto Serif Georgian' },
{ value: 'bpg-glaho', label: 'BPG Glaho' },
{ value: 'bpg-square', label: 'BPG Square' },
{ value: 'bpg-nino-mtavruli', label: 'BPG Nino Mtavruli (caps)' },
{ value: 'bpg-mrgvlovani', label: 'BPG Mrgvlovani' },
{ value: 'bpg-ingiri', label: 'BPG Ingiri (script)' },
{ value: 'bpg-rioni', label: 'BPG Rioni' },
{ value: 'bpg-irubaqidze', label: 'BPG Irubaqidze' },
{ value: 'bpg-banner', label: 'BPG Banner (caps)' }];


// ---- Visit analytics (logs page views to Supabase) ----
function logPageview() {
  if (!window.SupabaseClient || !window.SupabaseClient.logVisit) return;
  const ua = navigator.userAgent;
  const page = (window.location.hash || '').replace(/^#\/?/, '') || 'home';
  if (page === 'admin') return; // don't count admin visits
  const browser = /Edg/i.test(ua) ? 'Edge' : /OPR/i.test(ua) ? 'Opera' : /Chrome/i.test(ua) ? 'Chrome' : /Firefox/i.test(ua) ? 'Firefox' : /Safari/i.test(ua) ? 'Safari' : 'Unknown';
  const os = /Windows NT/i.test(ua) ? 'Windows' : /Mac OS X/i.test(ua) ? 'macOS' : /Android/i.test(ua) ? 'Android' : /iPhone|iPad/i.test(ua) ? 'iOS' : /Linux/i.test(ua) ? 'Linux' : 'Unknown';
  const device = /Mobi|Android|iPhone|iPad/i.test(ua) ? 'Mobile' : 'Desktop';
  window.SupabaseClient.logVisit({
    page,
    referrer: document.referrer || 'Direct',
    lang: navigator.language || '',
    device, browser, os
  });
}

// ---- Routing ----
const PAGE_ROUTES = ['courses', 'blog', 'gallery', 'reports', 'admin', 'syllabus'];
const parseRoute = () => {
  const h = (window.location.hash || '').replace(/^#\/?/, '');
  if (/^blog\/\d+$/.test(h)) return 'blogpost';
  return PAGE_ROUTES.includes(h) ? h : 'home';
};
const parsePostIndex = () => {
  const h = (window.location.hash || '').replace(/^#\/?/, '');
  const m = h.match(/^blog\/(\d+)$/);
  return m ? parseInt(m[1], 10) : null;
};

// ---- App ----
const App = () => {
  const tweaks = useTweaks(TWEAK_DEFAULTS);
  const [theme, setTheme] = useState(tweaks.values.theme || 'light');
  const [lang, setLang] = useState(tweaks.values.lang || 'ge');
  const [font, setFont] = useState(tweaks.values.font || 'noto');
  const [activeSection, setActiveSection] = useState('home');
  const [route, setRoute] = useState(parseRoute());
  const [postIndex, setPostIndex] = useState(parsePostIndex());

  useEffect(() => {
    const onHash = () => {
      const r = parseRoute();
      setRoute(r);
      setPostIndex(parsePostIndex());
      if (r !== 'home') {window.scrollTo(0, 0);return;}
      const h = (window.location.hash || '').replace(/^#\/?/, '');
      if (h && h !== 'home') {
        setTimeout(() => {
          const el = document.getElementById(h);
          if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: 'smooth' });
        }, 60);
      } else {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Log page views (initial load + each route change)
  useEffect(() => {
    logPageview();
    const onHashLog = () => logPageview();
    window.addEventListener('hashchange', onHashLog);
    return () => window.removeEventListener('hashchange', onHashLog);
  }, []);

  useEffect(() => {document.documentElement.dataset.theme = theme;}, [theme]);
  useEffect(() => {document.documentElement.dataset.font = font;}, [font]);

  useEffect(() => {
    const onScroll = () => {
      if (parseRoute() !== 'home') return;
      const sections = ['home', 'services', 'contact'];
      const scrollY = window.scrollY + 200;
      for (let i = sections.length - 1; i >= 0; i--) {
        const el = document.getElementById(sections[i]);
        if (el && el.offsetTop <= scrollY) {setActiveSection(sections[i]);break;}
      }
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const [, _cTick] = useState(0);
  useEffect(() => ContentStore.subscribe(() => _cTick((v) => v + 1)), []);

  const t = ContentStore.get(lang);

  if (route === 'admin') return <AdminPanel lang={lang} setLang={setLang} theme={theme} />;

  return (
    <>
      <ScrollProgress />
      <Navbar t={t} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} activeSection={activeSection} route={route} />
      {route === 'courses' ?
      <main className="subpage"><Courses t={t} /></main> :
      route === 'blogpost' ?
      <main className="subpage"><BlogPostPage t={t} lang={lang} index={postIndex} /></main> :
      route === 'syllabus' ?
      <main className="subpage"><SyllabusPage t={t} /></main> :
      route === 'blog' ?
      <main className="subpage"><Blog t={t} /></main> :
      route === 'gallery' ?
      <main className="subpage"><Gallery t={t} /></main> :
      route === 'reports' ?
      <main className="subpage"><ReportsPage t={t} /></main> :
      <>
        <Hero t={t} lang={lang} />
        <div className="section-divider" />
        <Services t={t} />
        <Testimonials t={t} lang={lang} />
        <div className="section-divider" />
        <Contact t={t} />
      </>}
      <Footer t={t} />
      <Floating t={t} />
      
      <TweaksPanel title="Tweaks">
        <TweakSection title="Appearance">
          <TweakRadio label="Theme" value={theme} onChange={(v) => {setTheme(v);tweaks.set('theme', v);}} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }]} />
          <TweakRadio label="Language" value={lang} onChange={(v) => {setLang(v);tweaks.set('lang', v);}} options={[{ value: 'en', label: 'EN' }, { value: 'ge', label: 'ქართული' }]} />
        </TweakSection>
        <TweakSection title="Typography">
          <TweakSelect label="Font family" value={font} onChange={(v) => {setFont(v);tweaks.set('font', v);}} options={FONT_OPTIONS} />
        </TweakSection>
      </TweaksPanel>
    </>);

};

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