// Sections: Manifesto, Services (sticky reveal), AI know-how, Numbers, Presence (map+cities), About, Contact, Footer

function Manifesto({ t }) {
  return (
    <section className="manifesto" data-screen-label="02 Manifesto">
      <div className="section-head">
        <span className="kicker">{t.manifesto.kicker}</span>
      </div>
      <div className="manifesto-body">
        <p className="manifesto-text">
          <SplitReveal text={t.manifesto.body} />
        </p>
      </div>
    </section>
  );
}

function Services({ t, lang }) {
  const items = t.services.items;
  return (
    <section id="services" className="services" data-screen-label="03 Services">
      <div className="section-head">
        <span className="kicker">{t.services.kicker}</span>
        <h2 className="section-title">
          <SplitReveal text={t.services.title} />
        </h2>
        <p className="section-sub">{t.services.sub}</p>
      </div>

      <div className="services-list">
        {items.map((it, i) => (
          <ServiceRow key={i} item={it} index={i} />
        ))}
      </div>
    </section>
  );
}

function ServiceRow({ item, index }) {
  const ref = React.useRef(null);
  const [hover, setHover] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const [visible, setVisible] = React.useState(true);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    if (r.top >= window.innerHeight) {
      setVisible(false);
      const io = new IntersectionObserver(entries => {
        entries.forEach(e => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
      }, { threshold: 0, rootMargin: '0px 0px -10% 0px' });
      io.observe(el);
      return () => io.disconnect();
    }
  }, []);

  return (
    <div
      ref={ref}
      className={`service-row ${visible ? 'is-in' : ''} ${hover || open ? 'is-hover' : ''} ${open ? 'is-open' : ''}`}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => setOpen(v => !v)}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(v => !v); } }}
      aria-expanded={open}
      aria-label={item.name}
      style={{ transitionDelay: `${index * 40}ms`, cursor: 'pointer' }}
    >
      <div className="service-tag">{item.tag}</div>
      <div className="service-name">{item.name}</div>
      <div className="service-desc">{item.desc}</div>
      <div className="service-arrow">
        <ArrowUpRight />
      </div>
    </div>
  );
}

function AIBlock({ t }) {
  return (
    <section className="ai-block" data-screen-label="04 AI">
      <div className="ai-grid">
        <div className="ai-left">
          <span className="kicker kicker-light">{t.ai.kicker}</span>
          <h2 className="ai-title">
            <SplitReveal text={t.ai.title} />
          </h2>
          <p className="ai-sub">{t.ai.sub}</p>
        </div>
        <div className="ai-right">
          {t.ai.points.map((p, i) => (
            <div key={i} className="ai-point">
              <div className="ai-point-k">
                <span className="ai-dot" />
                {p.k}
              </div>
              <div className="ai-point-v">{p.v}</div>
            </div>
          ))}

          <div className="ai-terminal" aria-hidden="true">
            <div className="ai-terminal-head">
              <span /><span /><span />
              <span className="ai-terminal-title">agent.run()</span>
            </div>
            <AITerminalBody />
          </div>
        </div>
      </div>
    </section>
  );
}

function AITerminalBody() {
  const lines = [
    { t: '→ parse(brief)', c: 'cmd' },
    { t: 'intent: launch GCC campaign', c: 'dim' },
    { t: '→ plan()', c: 'cmd' },
    { t: 'tasks: 7 · agents: 3', c: 'dim' },
    { t: '→ execute()', c: 'cmd' },
    { t: '✓ identity ready', c: 'ok' },
    { t: '✓ ads structured', c: 'ok' },
    { t: '✓ landing shipped', c: 'ok' },
    { t: 'ROAS est. 4.1x · handoff ready', c: 'hot' }
  ];
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setN(v => (v + 1) % (lines.length + 3)), 900);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="ai-terminal-body">
      {lines.slice(0, Math.min(n, lines.length)).map((l, i) => (
        <div key={i} className={`ai-line ai-line-${l.c}`}>{l.t}</div>
      ))}
      {n < lines.length && <div className="ai-cursor">▍</div>}
    </div>
  );
}

function Numbers({ t }) {
  return (
    <section className="numbers" data-screen-label="05 Numbers">
      <div className="section-head">
        <span className="kicker">{t.work.kicker}</span>
      </div>
      <div className="numbers-grid">
        {t.work.items.map((it, i) => (
          <div key={i} className="number-cell">
            <div className="number-n">
              <CountUp value={it.n} />
            </div>
            <div className="number-l">{it.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function CountUp({ value }) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(value);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const num = parseInt(String(value).replace(/\D/g, ''), 10);
    if (!num) { setShown(value); return; }
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const dur = 1400; const start = performance.now();
          const suffix = String(value).match(/\D+$/)?.[0] || '';
          const tick = (now) => {
            const p = Math.min(1, (now - start) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            setShown(Math.round(num * eased) + suffix);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.disconnect();
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [value]);
  return <span ref={ref}>{shown}</span>;
}

function Presence({ t }) {
  const [activeIdx, setActiveIdx] = React.useState(null);
  return (
    <section id="presence" className="presence" data-screen-label="06 Presence">
      <div className="section-head">
        <span className="kicker">{t.presence.kicker}</span>
        <h2 className="section-title">
          <SplitReveal text={t.presence.title} />
        </h2>
        <p className="section-sub">{t.presence.sub}</p>
      </div>

      <div className="presence-grid">
        <div className="presence-map">
          <WorldMap cities={t.presence.cities} activeIdx={activeIdx} />
        </div>

        <div className="presence-side">
          <div className="markets">
            <div className="markets-label">Markets</div>
            <div className="markets-list">
              {t.presence.markets.map((m, i) => (
                <div key={i} className="market-chip">
                  <span className="market-num">0{i + 1}</span>
                  <span className="market-name">{m}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="cities-list">
            {t.presence.cities.map((c, i) => (
              <CityCard
                key={i}
                city={c}
                index={i}
                active={activeIdx === i}
                onEnter={() => setActiveIdx(i)}
                onLeave={() => setActiveIdx(v => v === i ? null : v)}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function CityCard({ city, index, active, onEnter, onLeave }) {
  const time = useClock(city.tz);
  return (
    <div
      className={`city-card ${active ? 'is-active' : ''}`}
      style={{ transitionDelay: `${index * 60}ms` }}
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
      onFocus={onEnter}
      onBlur={onLeave}
      onTouchStart={onEnter}
      tabIndex={0}
    >
      <div className="city-card-head">
        <span className="city-card-idx">0{index + 1}</span>
        <span className="city-card-time">{time}</span>
      </div>
      <div className="city-card-name">{city.c}</div>
      <div className="city-card-role">{city.r}</div>
    </div>
  );
}

function WorldMap({ cities, activeIdx }) {
  const coords = {
    'Asia/Dubai': [55.27, 25.2],
    'Europe/Rome': [11.25, 43.77],
    'Asia/Yerevan': [44.51, 40.18],
    'Asia/Makassar': [115.19, -8.40],
    'America/Los_Angeles': [-118.24, 34.05]
  };
  const project = ([lng, lat]) => {
    const x = (lng + 180) * (1000 / 360);
    const y = (90 - lat) * (500 / 180);
    return [x, y];
  };

  return (
    <div className="worldmap-wrap">
      <svg viewBox="0 0 1000 500" className="worldmap-svg" aria-hidden="true" role="presentation">
        <WorldDots />
        {cities.map((c, i) => {
          const a = project(coords[c.tz] || [0, 0]);
          const next = cities[(i + 1) % cities.length];
          const b = project(coords[next.tz] || [0, 0]);
          return (
            <line key={i} x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]}
                  stroke="#E8192C" strokeOpacity="0.25" strokeWidth="1" strokeDasharray="2 4" />
          );
        })}
        {cities.map((c, i) => {
          const [x, y] = project(coords[c.tz] || [0, 0]);
          const isActive = activeIdx === i;
          return (
            <g key={i} className={`worldmap-pin ${isActive ? 'is-active' : ''}`}>
              <circle cx={x} cy={y} r={isActive ? 28 : 10} fill="#E8192C" opacity={isActive ? 0.35 : 0.2} style={{ transition: 'r 0.3s ease, opacity 0.3s ease' }}>
                <animate attributeName="r" values="10;22;10" dur="2.6s" begin={`${i * 0.3}s`} repeatCount="indefinite" />
                <animate attributeName="opacity" values="0.35;0;0.35" dur="2.6s" begin={`${i * 0.3}s`} repeatCount="indefinite" />
              </circle>
              <circle cx={x} cy={y} r={isActive ? 7 : 4} fill="#E8192C" style={{ transition: 'r 0.25s ease' }} />
              <text x={x + 10} y={y - 8} fill={isActive ? '#E8192C' : '#0A0A0B'} style={{ fontFamily: 'Unbounded, sans-serif', fontSize: '14px', fontWeight: 700, transition: 'fill 0.25s' }}>{c.c}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function WorldDots() {
  // A rough continents dot cloud — generated deterministically for a "gridded world" feel.
  // Reduce density on small viewports to save render time on mobile.
  const isSmall = typeof window !== 'undefined' && window.innerWidth < 720;
  const dots = React.useMemo(() => {
    const boxes = [
      [-168, 70, -52, 15],   // North America
      [-82, 12, -34, -55],   // South America
      [-11, 58, 40, 36],     // Europe
      [-18, 36, 52, -34],    // Africa
      [26, 70, 180, -10],    // Asia + SEA
      [113, -10, 155, -44],  // Australia
    ];
    const pts = [];
    const rand = (() => { let s = 7; return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; }; })();
    const perBox = isSmall ? 100 : 260;
    boxes.forEach(b => {
      for (let i = 0; i < perBox; i++) {
        const lng = b[0] + rand() * (b[2] - b[0]);
        const lat = b[1] + rand() * (b[3] - b[1]);
        const x = (lng + 180) * (1000 / 360);
        const y = (90 - lat) * (500 / 180);
        pts.push([x, y]);
      }
    });
    return pts;
  }, [isSmall]);
  return (
    <g>
      {dots.map(([x, y], i) => (
        <circle key={i} cx={x} cy={y} r="1.4" fill="#0A0A0B" opacity="0.35" />
      ))}
    </g>
  );
}

function About({ t }) {
  return (
    <section id="about" className="about" data-screen-label="07 About">
      <div className="about-grid">
        <div className="about-left">
          <span className="kicker">{t.about.kicker}</span>
          <div className="about-big">2014<span>→</span>2026</div>
        </div>
        <div className="about-right">
          <h2 className="section-title">
            <SplitReveal text={t.about.title} />
          </h2>
          <p className="about-body">{t.about.body}</p>
        </div>
      </div>
    </section>
  );
}

function Contact({ t, lang }) {
  return (
    <section id="contact" className="contact" data-screen-label="08 Contact">
      <div className="contact-inner">
        <span className="kicker kicker-light">{t.contact.kicker}</span>
        <h2 className="contact-title">
          <SplitReveal text={t.contact.title} />
        </h2>
        <p className="contact-sub">{t.contact.sub}</p>

        <a className="contact-cta" href={WA_LINK(lang)} target="_blank" rel="noopener noreferrer">
          <span className="contact-cta-icon">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M17.5 14.4c-.3-.15-1.8-.9-2.1-1-.28-.1-.48-.15-.68.15-.2.3-.78 1-1 1.2-.17.2-.35.22-.65.08-.3-.15-1.27-.47-2.42-1.5-.9-.8-1.5-1.8-1.67-2.1-.18-.3-.02-.46.13-.6.13-.13.3-.35.45-.52.15-.18.2-.3.3-.5.1-.2.05-.38-.02-.53-.07-.15-.67-1.6-.92-2.2-.24-.58-.48-.5-.67-.5-.17 0-.37-.02-.57-.02a1.1 1.1 0 0 0-.8.38c-.28.3-1.05 1.03-1.05 2.5s1.08 2.9 1.23 3.1c.15.2 2.1 3.2 5.1 4.5.72.3 1.28.47 1.72.6.72.23 1.38.2 1.9.12.58-.08 1.8-.72 2.05-1.42.25-.7.25-1.3.17-1.42-.07-.1-.27-.18-.57-.32zM12 2a10 10 0 0 0-8.5 15.2L2 22l4.9-1.4A10 10 0 1 0 12 2zm0 18.1a8.1 8.1 0 0 1-4.1-1.1l-.3-.2-2.9.8.8-2.8-.2-.3A8.1 8.1 0 1 1 12 20.1z"/></svg>
          </span>
          <span className="contact-cta-label">{t.cta.whatsapp}</span>
          <span className="contact-cta-arrow"><ArrowUpRight /></span>
        </a>

        <div className="contact-meta">
          <div><span>WhatsApp</span><a href={`tel:${t.contact.phone.replace(/\s/g,'')}`}>{t.contact.phone}</a></div>
          <div><span>Email</span><a href={`mailto:${t.contact.email}`}>{t.contact.email}</a></div>
          <div><span>Hours</span>{t.contact.hours}</div>
        </div>
      </div>
    </section>
  );
}

function Footer({ t }) {
  const year = new Date().getFullYear();
  return (
    <footer className="footer" aria-label="Site footer">
      <div className="footer-inner">
        <div className="footer-logo">
          <GULogo size={32} />
        </div>
        <nav className="footer-links" aria-label="Footer navigation">
          <a href="#">{ t.footer.offer}</a>
          <a href="#">{t.footer.policy}</a>
        </nav>
        <div className="footer-rights">© {year} GetUpper. {t.footer.rights}</div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Manifesto, Services, AIBlock, Numbers, Presence, About, Contact, Footer
});
