// Landing page for 67proxies — RESIDENTIAL-ONLY, worldwide pool, rotating, HTTP/HTTPS
const BANDWIDTH_PLANS = [
  { id: 'hour', name: '1 Hour',  price: 6.70, unit: 'hour',  gb: 'Unlimited', label: 'Burst testing', features: ['Unlimited residential bandwidth for 1 hour', 'Worldwide IP pool', 'HTTP / HTTPS', 'Rotating IPs', 'Ideal for quick jobs'] },
  { id: 'gb10', name: '10 GB',   price: 6.70, unit: '10 GB', gb: '10 GB',     label: 'Most popular',  popular: true, features: ['10 GB residential bandwidth', '30-day validity', 'Worldwide IP pool', 'HTTP / HTTPS', 'Rotating IPs'] },
];

// Dedicated-speed residential lanes. Each tier × duration is a separate plan.
const SPEED_TIERS = [
  { mbps: 100,  daily: 15,  weekly: 60,  monthly: 150  },
  { mbps: 250,  daily: 40,  weekly: 160, monthly: 400  },
  { mbps: 500,  daily: 75,  weekly: 300, monthly: 750  },
  { mbps: 1000, daily: 120, weekly: 480, monthly: 1200 },
];

// Flattened catalog used by the checkout + wallet system. IDs follow the pattern
// `mbps<speed>-<duration>` for speed plans, and raw ids for bandwidth plans.
const PLANS = [
  { id: 'hour', name: '1 Hour pass',        price: 6.70, gb: 'Unlimited', label: 'Burst testing', features: ['Unlimited residential for 1 hour', 'Worldwide pool', 'HTTP / HTTPS', 'Rotating IPs'] },
  { id: 'gb10', name: '10 GB Residential',  price: 6.70, gb: '10 GB',     label: 'Most popular', popular: true, features: ['10 GB residential bandwidth', '30-day validity', 'Worldwide pool'] },
  ...SPEED_TIERS.flatMap(t => [
    { id: `mbps${t.mbps}-daily`,   name: `${t.mbps} Mbps · Daily`,   price: t.daily,   gb: `${t.mbps} Mbps`, label: 'Dedicated speed', features: [`Dedicated ${t.mbps} Mbps residential`, '24 h unmetered', 'Worldwide pool'] },
    { id: `mbps${t.mbps}-weekly`,  name: `${t.mbps} Mbps · Weekly`,  price: t.weekly,  gb: `${t.mbps} Mbps`, label: 'Dedicated speed', features: [`Dedicated ${t.mbps} Mbps residential`, '7 days unmetered', 'Worldwide pool'] },
    { id: `mbps${t.mbps}-monthly`, name: `${t.mbps} Mbps · Monthly`, price: t.monthly, gb: `${t.mbps} Mbps`, label: 'Dedicated speed', features: [`Dedicated ${t.mbps} Mbps residential`, '30 days unmetered', 'Worldwide pool'] },
  ]),
];

function Landing({ onNav }) {
  // On first render: if ?ref=CODE is present, ping the server once per session
  // so it can count the view (for coupons) and — if it's a valid coupon —
  // stash the code in localStorage so the checkout flow can offer to pre-fill it.
  React.useEffect(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const refCode = params.get('ref');
      if (!refCode) return;
      const clean = refCode.trim().toUpperCase().slice(0, 32);
      const sessionKey = `67px_ref_seen_${clean}`;
      if (sessionStorage.getItem(sessionKey)) return;
      sessionStorage.setItem(sessionKey, '1');

      fetch(`/api/public/ref/${encodeURIComponent(clean)}`)
        .then(r => r.ok ? r.json() : null)
        .then(data => {
          if (!data) return;
          if (data.kind === 'coupon') {
            // Valid coupon — remember it for the checkout prefill
            localStorage.setItem('67px_coupon', data.code);
          } else {
            // Not a coupon — treat as a user referral code (for signup)
            localStorage.setItem('67px_ref', clean);
          }
        })
        .catch(() => {});
    } catch (_) {}
  }, []);

  return (
    <div style={{ background: 'var(--bg-0)', color: 'var(--fg-0)' }}>
      <LandingNav onNav={onNav} />
      <Hero onNav={onNav} />
      <Features />
      <LiveTerminal />
      <Pricing onNav={onNav} />
      <FAQ />
      <Contact onNav={onNav} />
      <Tos />
      <CTABand onNav={onNav} />
      <Footer />
    </div>
  );
}

function LandingNav({ onNav }) {
  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '18px 48px',
      background: 'rgba(7,9,13,0.8)', backdropFilter: 'blur(12px)',
      borderBottom: '1px solid var(--line-soft)',
    }}>
      <Logo67 size={26} />
      <div style={{ display: 'flex', gap: 28, fontSize: 14, color: 'var(--fg-1)' }}>
        <a href="#products">Products</a>
        <a href="#pricing">Pricing</a>
        <a href="#contact">Contact Us</a>
        <a href="#tos">TOS</a>
      </div>
      <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
        <button className="btn btn-ghost btn-sm" onClick={() => onNav('auth')}>Sign in</button>
        <button className="btn btn-primary btn-sm" onClick={() => onNav('signup')}>Get started <Icon name="arrow_right" size={14}/></button>
      </div>
    </nav>
  );
}

function Hero({ onNav }) {
  // CTA logic:
  //   - Not logged in: "Start from $6.70" → signup
  //   - Logged in, has at least one ACTIVE endpoint: "View your endpoints" → dashboard generator
  //   - Logged in, no active endpoints: "Go to dashboard" → dashboard balance/buy
  // This keeps the marketing landing useful even for returning customers,
  // who otherwise see a CTA aimed at strangers.
  const [hasProxies, setHasProxies] = React.useState(null);
  const [liveStats, setLiveStats]   = React.useState(null);
  const isLoggedIn = !!window.__user;

  React.useEffect(() => {
    if (!isLoggedIn) { setHasProxies(false); return; }
    window.api('/api/dashboard/proxies')
      .then(d => {
        const active = (d.proxies || []).filter(p => p.status !== 'expired');
        setHasProxies(active.length > 0);
      })
      .catch(() => setHasProxies(false));
  }, [isLoggedIn]);

  React.useEffect(() => {
    let cancelled = false;
    fetch('/api/public/stats')
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d && !cancelled) setLiveStats(d); })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  const fmtIPs = (n) => {
    if (!n) return '1.3M+';   // graceful fallback during initial load
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(2).replace(/\.?0+$/, '') + 'M+';
    return Math.round(n / 1000) + 'K+';
  };
  const ipsLabel = fmtIPs(liveStats?.ips);

  const ctaLabel = !isLoggedIn
    ? 'Start from $6.70'
    : hasProxies
      ? 'View your endpoints'
      : 'Go to dashboard';
  const ctaTarget = !isLoggedIn
    ? 'signup'
    : 'dashboard';
  const ctaSection = hasProxies ? 'generator' : null;

  const handleCta = () => {
    onNav(ctaTarget);
    // After the dashboard mounts, jump to the right section
    if (ctaSection) {
      setTimeout(() => {
        if (window.__setSection) window.__setSection(ctaSection);
      }, 50);
    }
  };

  return (
    <section style={{ position: 'relative', padding: '80px 48px 60px', overflow: 'hidden' }}>
      <HeroBackdrop/>
      <div style={{ maxWidth: 1200, margin: '0 auto', position: 'relative' }}>
        <div className="chip chip-accent" style={{ marginBottom: 24 }}>
          <span className="dot" style={{ background: 'var(--accent)' }}/> {ipsLabel} residential IPs live now
        </div>
        <h1 style={{
          fontSize: 'clamp(48px, 6vw, 88px)', fontWeight: 500, lineHeight: 0.95,
          letterSpacing: '-0.035em', margin: '0 0 24px', maxWidth: 980, textWrap: 'balance',
        }}>
          The residential proxy<br/>built for <span style={{ color: 'var(--accent)', fontStyle: 'italic', fontWeight: 400 }}>relentless</span> scrapers.
        </h1>
        <p style={{ fontSize: 19, color: 'var(--fg-1)', maxWidth: 620, lineHeight: 1.5, margin: '0 0 36px' }}>
          {ipsLabel} real residential IPs in a single worldwide pool. Rotating, unmetered, unstoppable.
          Pay in crypto. Generate in seconds. Scrape without seeing a CAPTCHA again.
        </p>
        <div style={{ display: 'flex', gap: 12, marginBottom: 56 }}>
          <button className="btn btn-primary" onClick={handleCta}>
            {ctaLabel} <Icon name={hasProxies ? 'arrow_right' : 'arrow_right'} size={14}/>
          </button>
        </div>
        <HeroStats />
      </div>
    </section>
  );
}

function HeroBackdrop() {
  // Simple, quiet backdrop: dual color wash + masked micro-grid. No globe, no orbits.
  return (
    <div aria-hidden="true" style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse 60% 55% at 80% 15%, color-mix(in oklab, var(--accent) 18%, transparent), transparent 60%), radial-gradient(ellipse 55% 50% at 10% 90%, color-mix(in oklab, var(--accent) 10%, #4b8bf5 30%), transparent 55%)',
      }}/>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px)',
        backgroundSize: '56px 56px',
        maskImage: 'radial-gradient(ellipse 80% 80% at 50% 40%, black 30%, transparent 85%)',
      }}/>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(to bottom, transparent 60%, var(--bg-0))',
      }}/>
    </div>
  );
}

function HeroStats() {
  const [stats, setStats] = React.useState(null);

  // Fetch on mount + refresh every 60s. The backend re-rolls the values every
  // 5–10 minutes; polling more frequently is wasted bandwidth.
  React.useEffect(() => {
    let cancelled = false;
    const load = () => {
      fetch('/api/public/stats')
        .then(r => r.ok ? r.json() : null)
        .then(d => { if (d && !cancelled) setStats(d); })
        .catch(() => {});
    };
    load();
    const t = setInterval(load, 60_000);
    return () => { cancelled = true; clearInterval(t); };
  }, []);

  // Render falls back to placeholder dashes until the first fetch lands.
  // The actual numbers and ranges are server-controlled.
  const fmtIPs = (n) => {
    if (!n) return '—';
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(2).replace(/\.?0+$/, '') + 'M+';
    return (n / 1000).toFixed(0) + 'K+';
  };

  const cards = [
    { k: fmtIPs(stats?.ips),                                          v: 'Residential IPs' },
    { k: stats ? `${stats.successRate.toFixed(2)}%` : '—',            v: 'Success rate' },
    { k: stats ? `${stats.avgResponseMs}ms` : '—',                    v: 'Avg response time' },
  ];

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
      border: '1px solid var(--line)', borderRadius: 14, background: 'var(--bg-1)',
      overflow: 'hidden',
    }}>
      {cards.map((s, i) => (
        <div key={s.v} style={{
          padding: '24px 28px',
          borderRight: i < cards.length - 1 ? '1px solid var(--line)' : 'none',
        }}>
          <div className="mono" style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--fg-0)' }}>{s.k}</div>
          <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4 }}>{s.v}</div>
        </div>
      ))}
    </div>
  );
}

function Features() {
  const items = [
    { icon: 'globe', title: 'Worldwide pool', line: 'IPs from real ISPs across every region, single global endpoint', color: 'var(--accent)' },
    { icon: 'refresh', title: 'Rotating by default', line: 'Fresh IP on every request, no session stickiness', color: '#7aa7f7' },
    { icon: 'bolt', title: 'Unmetered options', line: 'Hourly, daily, or full unlimited month plans', color: '#f2b95a' },
    { icon: 'shield', title: 'Clean & compliant', line: 'Opt-in peers, monitored network, no abuse', color: '#b39bf7' },
  ];
  return (
    <section id="products" style={{ padding: '96px 48px', maxWidth: 1200, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 48 }}>
        <div>
          <div className="chip" style={{ marginBottom: 16 }}>One product, one promise</div>
          <h2 style={{ fontSize: 44, fontWeight: 500, letterSpacing: '-0.03em', margin: 0, maxWidth: 620 }}>
            Residential IPs. Nothing else to learn.
          </h2>
        </div>
        <div style={{ fontSize: 14, color: 'var(--fg-2)', maxWidth: 360 }}>
          No datacenter, mobile, or ISP SKUs. A single worldwide residential pool that just works.
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        {items.map(it => (
          <div key={it.title} className="card" style={{ padding: 28, position: 'relative', overflow: 'hidden' }}>
            <div style={{
              width: 44, height: 44, borderRadius: 10,
              background: `color-mix(in oklab, ${it.color} 15%, transparent)`,
              display: 'grid', placeItems: 'center', marginBottom: 24,
              border: `1px solid color-mix(in oklab, ${it.color} 30%, transparent)`,
            }}>
              <Icon name={it.icon} size={20} color={it.color} />
            </div>
            <div style={{ fontSize: 20, fontWeight: 500, letterSpacing: '-0.015em', marginBottom: 6 }}>{it.title}</div>
            <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5 }}>{it.line}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function LiveTerminal() {
  const [step, setStep] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setStep(s => (s + 1) % 6), 1400); return () => clearInterval(t); }, []);
  const lines = [
    { t: '$ curl --proxy network.67proxies.com:67 -U user_a3f2c1b4d5:pw https://ipinfo.io', fg: 'var(--fg-0)' },
    { t: '{', fg: 'var(--fg-2)' },
    { t: '  "ip": "185.199.247.142",', fg: 'var(--accent)' },
    { t: '  "type": "residential",', fg: 'var(--fg-1)' },
    { t: '  "rotating": true, "pool": "worldwide"', fg: 'var(--fg-1)' },
    { t: '}', fg: 'var(--fg-2)' },
  ];
  return (
    <section style={{ padding: '40px 48px 96px', maxWidth: 1200, margin: '0 auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 48, alignItems: 'center' }}>
        <div>
          <div className="chip" style={{ marginBottom: 16 }}>Developer experience</div>
          <h2 style={{ fontSize: 38, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 20px' }}>
            Drop-in endpoint.<br/>No SDK. No setup.
          </h2>
          <p style={{ fontSize: 16, color: 'var(--fg-1)', lineHeight: 1.5, marginBottom: 24 }}>
            One host, one port, standard HTTP/SOCKS5. Every request grabs a fresh residential IP from the worldwide pool — no sessions, no pinning.
            Works with curl, requests, Puppeteer, Selenium, Scrapy — anything that speaks proxies.
          </p>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {['curl', 'Python', 'Node', 'Go', 'Puppeteer', 'Selenium'].map(t => <span key={t} className="chip mono">{t}</span>)}
          </div>
        </div>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '10px 14px', borderBottom: '1px solid var(--line)',
            background: 'var(--bg-2)',
          }}>
            <span className="dot" style={{ background: '#ff5f56' }}/>
            <span className="dot" style={{ background: '#ffbd2e' }}/>
            <span className="dot" style={{ background: '#27c93f' }}/>
            <span style={{ fontSize: 12, color: 'var(--fg-2)', marginLeft: 8 }} className="mono">~/scraper — zsh</span>
          </div>
          <div className="mono" style={{ padding: 24, fontSize: 13, lineHeight: 1.7 }}>
            {lines.slice(0, step + 1).map((l, i) => (
              <div key={i} style={{ color: l.fg, whiteSpace: 'pre' }}>
                {l.t}{i === step && <span style={{ background: 'var(--accent)', display: 'inline-block', width: 8, height: 14, verticalAlign: 'middle', marginLeft: 2, animation: 'blink 1s steps(1) infinite' }}/>}
              </div>
            ))}
          </div>
        </div>
      </div>
      <style>{`@keyframes blink { 50% { opacity: 0; } }`}</style>
    </section>
  );
}

function Pricing({ onNav }) {
  const go = () => onNav(window.__user ? 'dashboard' : 'signup');

  return (
    <section id="pricing" style={{ padding: '96px 48px', background: 'var(--bg-1)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <div className="chip" style={{ marginBottom: 16 }}>Pricing</div>
          <h2 style={{ fontSize: 44, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 16px' }}>
            Residential. Rotating. Simple.
          </h2>
          <p style={{ fontSize: 16, color: 'var(--fg-2)', margin: 0, maxWidth: 620, marginLeft: 'auto', marginRight: 'auto' }}>
            Pay as you go with bandwidth passes, or lock in a dedicated speed lane.
          </p>
        </div>

        {/* Bandwidth — 2 hero cards, centered */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 400px))', gap: 16, justifyContent: 'center', marginBottom: 48 }}>
          {BANDWIDTH_PLANS.map(p => (
            <div key={p.id} className="card" style={{
              padding: 32, position: 'relative',
              border: p.popular ? '1px solid var(--accent)' : '1px solid var(--line)',
              background: p.popular ? 'linear-gradient(180deg, rgba(61,220,196,0.05), var(--bg-1) 40%)' : 'var(--bg-1)',
            }}>
              {p.popular && <div style={{
                position: 'absolute', top: -12, right: 24,
                background: 'var(--accent)', color: 'var(--accent-ink)',
                fontSize: 11, fontWeight: 600, letterSpacing: '0.05em',
                padding: '4px 10px', borderRadius: 999, textTransform: 'uppercase',
              }}>Most popular</div>}
              <div style={{ fontSize: 13, color: 'var(--fg-2)', marginBottom: 4 }}>{p.label}</div>
              <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 20 }}>{p.name}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 6 }}>
                <span className="mono" style={{ fontSize: 48, fontWeight: 500, letterSpacing: '-0.03em' }}>
                  ${Number.isInteger(p.price)
                    ? p.price.toLocaleString('en-US')
                    : p.price.toFixed(2)}
                </span>
                <span style={{ fontSize: 14, color: 'var(--fg-2)' }}>/ {p.unit}</span>
              </div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 24 }}>
                {p.id === 'hour' ? 'Unlimited bandwidth · 1 hour' : '10 GB · 30-day validity'}
              </div>
              <button
                onClick={go}
                className={p.popular ? 'btn btn-primary' : 'btn btn-ghost'}
                style={{ width: '100%', justifyContent: 'center', marginBottom: 28 }}
              >Get {p.name}</button>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {p.features.map(f => (
                  <div key={f} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: 'var(--fg-1)' }}>
                    <Icon name="check" size={14} color="var(--accent)"/>{f}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        {/* Dedicated speed lanes — tier × duration grid */}
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <div className="chip chip-accent" style={{ marginBottom: 12 }}>Dedicated speed</div>
          <h3 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 8px' }}>
            Lock in a guaranteed pipe.
          </h3>
          <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: 0 }}>
            Unmetered bandwidth at a fixed speed for your chosen window.
          </p>
        </div>

        <div className="card" style={{ padding: 0, overflow: 'hidden', marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '140px repeat(3, 1fr) 140px' }}>
            {/* Header row */}
            <div style={{ padding: '14px 20px', fontSize: 11, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: '1px solid var(--line)', background: 'var(--bg-2)' }}>Speed</div>
            {['Daily', 'Weekly', 'Monthly'].map(h => (
              <div key={h} style={{ padding: '14px 20px', fontSize: 11, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: '1px solid var(--line)', background: 'var(--bg-2)', textAlign: 'center' }}>{h}</div>
            ))}
            <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)', background: 'var(--bg-2)' }}/>

            {/* Tier rows */}
            {SPEED_TIERS.map((t, ri) => (
              <React.Fragment key={t.mbps}>
                <div style={{ padding: '20px', borderBottom: ri < SPEED_TIERS.length - 1 ? '1px solid var(--line-soft)' : 'none', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span className="mono" style={{ fontSize: 20, fontWeight: 500, letterSpacing: '-0.02em' }}>{t.mbps}</span>
                  <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>Mbps</span>
                </div>
                {['daily', 'weekly', 'monthly'].map(dur => (
                  <div key={dur} style={{ padding: 20, borderBottom: ri < SPEED_TIERS.length - 1 ? '1px solid var(--line-soft)' : 'none', textAlign: 'center' }}>
                    <div className="mono" style={{ fontSize: 20, fontWeight: 500 }}>
                      ${Number(t[dur]).toLocaleString('en-US')}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                      {dur === 'daily' ? '24 h' : dur === 'weekly' ? '7 days' : '30 days'}
                    </div>
                  </div>
                ))}
                <div style={{ padding: 20, borderBottom: ri < SPEED_TIERS.length - 1 ? '1px solid var(--line-soft)' : 'none', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                  <button className="btn btn-ghost btn-sm" onClick={go}>Get →</button>
                </div>
              </React.Fragment>
            ))}
          </div>
        </div>

        <div style={{ textAlign: 'center', marginTop: 32, fontSize: 13, color: 'var(--fg-2)' }}>
          Need more? <a href="#contact" style={{ color: 'var(--accent)' }}>Contact us</a> for custom lanes and volume pricing.
        </div>
      </div>
    </section>
  );
}

function GlobeStats() {
  const regions = [
    { r: 'North America', ips: '18.4M', lat: '42ms' },
    { r: 'Europe', ips: '22.1M', lat: '38ms' },
    { r: 'Asia Pacific', ips: '19.8M', lat: '61ms' },
    { r: 'LATAM', ips: '4.2M', lat: '78ms' },
    { r: 'Middle East', ips: '1.9M', lat: '89ms' },
    { r: 'Africa', ips: '0.8M', lat: '104ms' },
  ];
  return (
    <section id="network" style={{ padding: '96px 48px', maxWidth: 1200, margin: '0 auto' }}>
      <div style={{ marginBottom: 48 }}>
        <div className="chip" style={{ marginBottom: 16 }}>Global network</div>
        <h2 style={{ fontSize: 44, fontWeight: 500, letterSpacing: '-0.03em', margin: 0, maxWidth: 720 }}>
          One worldwide pool. Real residential IPs. Zero dead nodes.
        </h2>
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr' }}>
          <NetworkMap/>
          <div style={{ borderLeft: '1px solid var(--line)' }}>
            {regions.map((r, i) => (
              <div key={r.r} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '20px 28px',
                borderBottom: i < regions.length - 1 ? '1px solid var(--line-soft)' : 'none',
              }}>
                <div style={{ fontSize: 15, fontWeight: 500 }}>{r.r}</div>
                <div style={{ display: 'flex', gap: 28, alignItems: 'center' }}>
                  <span className="mono" style={{ fontSize: 14, color: 'var(--accent)' }}>{r.ips}</span>
                  <span className="mono" style={{ fontSize: 13, color: 'var(--fg-2)' }}>{r.lat}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function NetworkMap() {
  // Real-ish world map using a hand-tuned dot-matrix mask shaped like actual continents.
  // Each string is a horizontal slice of the globe (lat band); '#' = landmass dot.
  const LAND = [
    // 0         1         2         3         4         5         6         7
    // 01234567890123456789012345678901234567890123456789012345678901234567890123456789
    '     ####### ############                                                       ',
    '    ######################         #####    ###  ########### ##########         ',
    '   ########################       #########  ##  #############################  ',
    '    ######################       ###############  ######################### ### ',
    '     ####################         #############    ################## ####      ',
    '       ################           ############      ###############             ',
    '         ###########                #########        ############# ####          ',
    '          ########                  ##########        ###########               ',
    '             ####                  ###########         ###### ####              ',
    '              ####                 ############         ####                    ',
    '              #####                ############          ##                     ',
    '               #####               ###########                     ######       ',
    '                #####               #########                     ##########    ',
    '                 ####                #######                       ########     ',
    '                  ####                ####                          ###         ',
    '                   ##                   #                                       ',
    '                    #                                                           ',
    '                                                                                ',
  ];
  const COLS = LAND[0].length;
  const ROWS = LAND.length;

  // Nodes positioned in roughly realistic locations (col, row) inside the grid above.
  const nodes = [
    { x: 10, y: 2,  r: 'NA' },  // US West
    { x: 16, y: 2,  r: 'NA' },  // US Central
    { x: 20, y: 3,  r: 'NA' },  // US East
    { x: 14, y: 1,  r: 'NA' },  // Canada
    { x: 16, y: 10, r: 'LATAM' },// Brazil
    { x: 17, y: 12, r: 'LATAM' },// Argentina
    { x: 41, y: 1,  r: 'EU' },  // UK
    { x: 44, y: 2,  r: 'EU' },  // Germany
    { x: 47, y: 2,  r: 'EU' },  // Poland
    { x: 45, y: 3,  r: 'EU' },  // Italy
    { x: 48, y: 4,  r: 'ME' },  // Turkey
    { x: 51, y: 5,  r: 'ME' },  // Saudi
    { x: 44, y: 7,  r: 'AF' },  // W. Africa
    { x: 46, y: 10, r: 'AF' },  // Kenya
    { x: 47, y: 13, r: 'AF' },  // South Africa
    { x: 58, y: 2,  r: 'APAC' },// C. Asia
    { x: 62, y: 2,  r: 'APAC' },// China
    { x: 66, y: 2,  r: 'APAC' },// Japan
    { x: 70, y: 3,  r: 'APAC' },// Japan E
    { x: 56, y: 5,  r: 'APAC' },// India
    { x: 64, y: 6,  r: 'APAC' },// SE Asia
    { x: 67, y: 8,  r: 'APAC' },// Indonesia
    { x: 68, y: 12, r: 'APAC' },// Australia W
    { x: 71, y: 12, r: 'APAC' },// Australia E
  ];

  const W = COLS * 4;
  const H = ROWS * 4;

  return (
    <div style={{ position: 'relative', minHeight: 380, padding: 24, background: 'radial-gradient(ellipse at 40% 45%, color-mix(in oklab, var(--accent) 12%, transparent), transparent 65%)' }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        <defs>
          <radialGradient id="nodeGlow">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.7"/>
            <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.15"/>
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
          </radialGradient>
          <filter id="softBlur" x="-20%" y="-20%" width="140%" height="140%">
            <feGaussianBlur stdDeviation="0.5"/>
          </filter>
        </defs>

        {/* Dotted landmasses */}
        {LAND.flatMap((row, ry) =>
          [...row].map((ch, rx) => {
            if (ch !== '#') return null;
            // Distance to closest node — dots near active nodes glow brighter.
            let minD = 999;
            for (const n of nodes) {
              const d = Math.hypot(n.x - rx, n.y - ry);
              if (d < minD) minD = d;
            }
            const near = minD < 3.5;
            const cx = rx * 4 + 2;
            const cy = ry * 4 + 2;
            return (
              <circle
                key={`${rx}-${ry}`}
                cx={cx}
                cy={cy}
                r={near ? 0.95 : 0.7}
                fill={near ? 'var(--accent)' : 'var(--fg-2)'}
                opacity={near ? 0.55 - minD * 0.09 : 0.22}
              />
            );
          })
        )}

        {/* Node glows */}
        {nodes.map((n, i) => (
          <circle
            key={`g${i}`}
            cx={n.x * 4 + 2}
            cy={n.y * 4 + 2}
            r={8}
            fill="url(#nodeGlow)"
          />
        ))}

        {/* Node cores with subtle pulse */}
        {nodes.map((n, i) => (
          <g key={`n${i}`}>
            <circle
              cx={n.x * 4 + 2}
              cy={n.y * 4 + 2}
              r={2.8}
              fill="var(--accent)"
              opacity="0.15"
            >
              <animate attributeName="r" values="2.8;5;2.8" dur={`${3 + (i % 4) * 0.6}s`} repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0.3;0;0.3" dur={`${3 + (i % 4) * 0.6}s`} repeatCount="indefinite"/>
            </circle>
            <circle
              cx={n.x * 4 + 2}
              cy={n.y * 4 + 2}
              r={1.4}
              fill="var(--accent)"
            />
            <circle
              cx={n.x * 4 + 2}
              cy={n.y * 4 + 2}
              r={0.6}
              fill="#fff"
            />
          </g>
        ))}

        {/* Traffic arcs between select pairs */}
        {[
          [nodes[2], nodes[8]],   // US East ↔ Germany
          [nodes[8], nodes[17]],  // Germany ↔ China
          [nodes[2], nodes[18]],  // US East ↔ Japan
          [nodes[8], nodes[16]],  // Germany ↔ India
          [nodes[17], nodes[21]], // China ↔ Australia
          [nodes[0], nodes[18]],  // US West ↔ Japan
        ].map(([a, b], i) => {
          const ax = a.x * 4 + 2, ay = a.y * 4 + 2;
          const bx = b.x * 4 + 2, by = b.y * 4 + 2;
          const mx = (ax + bx) / 2;
          const my = (ay + by) / 2 - Math.abs(bx - ax) * 0.3;
          return (
            <g key={`arc${i}`}>
              <path
                d={`M ${ax} ${ay} Q ${mx} ${my} ${bx} ${by}`}
                fill="none"
                stroke="var(--accent)"
                strokeWidth="0.3"
                opacity="0.35"
                strokeDasharray="1.5 1.5"
              />
              <circle r="0.7" fill="var(--accent)">
                <animateMotion dur={`${4 + i * 0.5}s`} repeatCount="indefinite" path={`M ${ax} ${ay} Q ${mx} ${my} ${bx} ${by}`}/>
              </circle>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function FAQ() {
  const items = [
    { q: 'How does bandwidth pricing work?', a: 'You pay only for traffic that successfully reaches the target. Failed requests, timeouts, and our retries are never billed. Unused GB roll over for 90 days.' },
    { q: 'Can I pick a country or sticky session?', a: 'No — 67proxies is built around a single worldwide rotating pool. Every request gets a fresh residential IP from wherever in the network delivers fastest. Simpler, faster, cheaper.' },
    { q: 'What payment methods do you accept?', a: 'Crypto via OxaPay (USDT, BTC, ETH, LTC, TRX, and 8 more), plus credit card and wire for enterprise.' },
    { q: 'Do you log my requests?', a: 'We log only metadata required for billing (timestamp, bytes). Request URLs and response bodies are never stored. Full transparency report published quarterly.' },
  ];
  return (
    <section style={{ padding: '96px 48px', maxWidth: 900, margin: '0 auto' }}>
      <h2 style={{ fontSize: 44, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 48px', textAlign: 'center' }}>Frequently asked</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {items.map((it, i) => <FAQItem key={i} {...it}/>)}
      </div>
    </section>
  );
}
function FAQItem({ q, a }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ borderBottom: '1px solid var(--line)' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: '100%', padding: '20px 0', display: 'flex',
        justifyContent: 'space-between', alignItems: 'center',
        fontSize: 17, fontWeight: 500, color: 'var(--fg-0)', textAlign: 'left',
      }}>
        {q}
        <Icon name={open ? 'x' : 'plus'} size={16} color="var(--fg-2)"/>
      </button>
      {open && <div style={{ paddingBottom: 20, fontSize: 14, color: 'var(--fg-1)', lineHeight: 1.6, maxWidth: 680 }}>{a}</div>}
    </div>
  );
}

function CTABand({ onNav }) {
  return (
    <section style={{ padding: '48px', background: 'var(--bg-1)' }}>
      <div className="card" style={{
        maxWidth: 1200, margin: '0 auto', padding: '64px 56px',
        background: 'linear-gradient(135deg, var(--bg-2), var(--bg-1))',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -100, right: -100, width: 400, height: 400,
          background: 'radial-gradient(circle, var(--accent-glow), transparent 60%)',
        }}/>
        <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 48 }}>
          <div>
            <h2 style={{ fontSize: 38, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 12px', maxWidth: 560 }}>
              Ready to outrun the CAPTCHA?
            </h2>
            <p style={{ fontSize: 15, color: 'var(--fg-1)', margin: 0 }}>Pay in crypto. Top up any amount. Use it whenever.</p>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <button className="btn btn-ghost" onClick={() => onNav(window.__user ? 'dashboard' : 'auth')}>
              {window.__user ? 'Open dashboard' : 'Sign in'}
            </button>
            <button className="btn btn-primary" onClick={() => onNav(window.__user ? 'dashboard' : 'signup')}>
              Get started <Icon name="arrow_right" size={14}/>
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  const cols = [
    { h: 'Products', links: ['Residential Unlimited', '1 Gbps · 1 Day', '1 Gbps · 1 Week', 'API access'] },
    { h: 'Use cases', links: ['Web scraping', 'Ad verification', 'SEO & SERP', 'Brand protection', 'Market research'] },
    { h: 'Developers', links: ['Documentation', 'API reference', 'Status', 'Changelog', 'Integrations'] },
    { h: 'Company', links: ['About', 'Blog', 'Careers', 'Press kit', 'Contact'] },
    { h: 'Legal', links: ['Acceptable use', 'Privacy', 'Terms', 'DPA', 'Transparency report'] },
  ];
  return (
    <footer style={{ padding: '72px 48px 32px', borderTop: '1px solid var(--line)' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr repeat(5, 1fr)', gap: 40, marginBottom: 48 }}>
          <div>
            <Logo67 size={26}/>
            <p style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.6, marginTop: 16, maxWidth: 260 }}>
              The proxy network built for relentless scrapers. Since 2021.
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
              <div className="chip"><span className="dot" style={{ background: 'var(--ok)' }}/> All systems normal</div>
            </div>
          </div>
          {cols.map(col => (
            <div key={col.h}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 16 }}>{col.h}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {col.links.map(l => <a key={l} style={{ fontSize: 13, color: 'var(--fg-1)' }}>{l}</a>)}
              </div>
            </div>
          ))}
        </div>
        <div style={{
          paddingTop: 24, borderTop: '1px solid var(--line-soft)',
          display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--fg-3)',
        }}>
          <div>© 2026 67proxies, Inc.</div>
          <div className="mono">build 2026.04.21 · us-east-1</div>
        </div>
      </div>
    </footer>
  );
}

function Contact({ onNav }) {
  const [sent, setSent] = React.useState(null);   // { ticketId } when created
  const [sending, setSending] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', email: '', subject: '', body: '' });
  const [err, setErr] = React.useState(null);

  const canSend =
    form.email &&
    form.subject.trim().length >= 3 &&
    form.body.trim().length >= 10 &&
    !sending;

  const submit = async (e) => {
    e.preventDefault();
    if (!canSend) return;
    setSending(true); setErr(null);
    try {
      const res = await fetch('/api/public/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error('send_failed');
      const data = await res.json().catch(() => ({}));
      setSent({ ticketId: data.ticket_id || null });
    } catch (_) {
      setErr('Could not submit right now. Please try again or email support@67proxies.com.');
      setSending(false);
    }
  };

  return (
    <section id="contact" style={{ padding: '96px 48px', borderTop: '1px solid var(--line)' }}>
      <div style={{ maxWidth: 980, margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 48, alignItems: 'start' }}>
        <div>
          <div className="chip" style={{ marginBottom: 16 }}>Support</div>
          <h2 style={{ fontSize: 40, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 16px' }}>
            Open a ticket.
          </h2>
          <p style={{ fontSize: 15, color: 'var(--fg-2)', lineHeight: 1.6, margin: '0 0 24px' }}>
            Volume pricing, custom lanes, integration help, or something on fire — submit a ticket and we'll reply fast.
            Track the conversation from your dashboard any time.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, fontSize: 13 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--fg-1)' }}>
              <Icon name="mail" size={14} color="var(--accent)"/> support@67proxies.com
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--fg-1)' }}>
              <Icon name="globe" size={14} color="var(--accent)"/> Response within 2 hours · 24/7
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--fg-1)' }}>
              <Icon name="shield" size={14} color="var(--accent)"/> Encrypted end-to-end
            </div>
          </div>
        </div>

        <form onSubmit={submit} className="card" style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {sent ? (
            <div style={{ textAlign: 'center', padding: '24px 0' }}>
              <div style={{
                width: 48, height: 48, borderRadius: '50%',
                background: 'color-mix(in oklab, var(--ok) 20%, transparent)',
                display: 'grid', placeItems: 'center', margin: '0 auto 16px',
              }}>
                <Icon name="check" size={22} color="var(--ok)"/>
              </div>
              <div style={{ fontSize: 17, fontWeight: 500, marginBottom: 6 }}>
                Ticket created{sent.ticketId ? ` · #${sent.ticketId}` : ''}
              </div>
              <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.6, marginBottom: 18 }}>
                We'll reply to <b>{form.email}</b>. You can also sign in to see the conversation in your dashboard.
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => onNav && onNav('auth')}>Sign in to track</button>
            </div>
          ) : (
            <>
              <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 4 }}>Create a ticket</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 8 }}>
                Have an account? <a onClick={() => onNav && onNav('auth')} style={{ color: 'var(--accent)', cursor: 'pointer' }}>Sign in</a> to open tickets from your dashboard.
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div>
                  <label style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'block', marginBottom: 6 }}>Name</label>
                  <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Your name" maxLength={80} style={{ width: '100%' }}/>
                </div>
                <div>
                  <label style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'block', marginBottom: 6 }}>Email *</label>
                  <input type="email" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="Your email" maxLength={254} style={{ width: '100%' }}/>
                </div>
              </div>
              <div>
                <label style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'block', marginBottom: 6 }}>Subject *</label>
                <input required value={form.subject} onChange={e => setForm({ ...form, subject: e.target.value })} placeholder="Volume pricing for 5 TB/mo" maxLength={140} style={{ width: '100%' }}/>
              </div>
              <div>
                <label style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'block', marginBottom: 6 }}>Message *</label>
                <textarea required value={form.body} onChange={e => setForm({ ...form, body: e.target.value })} placeholder="Tell us what you need…" rows={5} maxLength={4000} style={{ width: '100%', resize: 'vertical', fontFamily: 'inherit' }}/>
              </div>
              {err && (
                <div role="alert" style={{ fontSize: 12, color: 'var(--err)', background: 'color-mix(in oklab, var(--err) 10%, transparent)', border: '1px solid color-mix(in oklab, var(--err) 30%, transparent)', padding: '9px 12px', borderRadius: 8 }}>
                  {err}
                </div>
              )}
              <button type="submit" className="btn btn-primary" disabled={!canSend} style={{ justifyContent: 'center', padding: '11px 16px', opacity: canSend ? 1 : 0.6 }}>
                {sending ? 'Submitting…' : 'Submit ticket'} <Icon name="arrow_right" size={14}/>
              </button>
            </>
          )}
        </form>
      </div>
    </section>
  );
}

function Tos() {
  return (
    <section id="tos" style={{ padding: '96px 48px', background: 'var(--bg-1)', borderTop: '1px solid var(--line)' }}>
      <div style={{ maxWidth: 820, margin: '0 auto' }}>
        <div className="chip" style={{ marginBottom: 16 }}>Legal</div>
        <h2 style={{ fontSize: 40, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 12px' }}>Terms of Service</h2>
        <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: '0 0 32px' }}>Last updated: April 21, 2026</p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 24, fontSize: 14, lineHeight: 1.7, color: 'var(--fg-1)' }}>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 500, margin: '0 0 8px', color: 'var(--fg-0)' }}>1. Acceptable use</h3>
            You may use the service for lawful scraping, market research, ad verification, brand protection,
            SEO monitoring, and comparable business purposes. You may not use the service to target any
            individual, harass, stalk, commit fraud, launch DDoS attacks, interfere with critical
            infrastructure, or violate any applicable law.
          </div>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 500, margin: '0 0 8px', color: 'var(--fg-0)' }}>2. Account & security</h3>
            You are responsible for keeping your credentials safe. API keys are shown once at creation and cannot
            be recovered afterwards. Share and rotate them like any other secret.
          </div>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 500, margin: '0 0 8px', color: 'var(--fg-0)' }}>3. Billing</h3>
            Plans are prepaid in supported cryptocurrencies. Bandwidth packs roll over within the stated validity
            window and are non-refundable once traffic has been served. Speed lanes activate on successful
            confirmation and end at the stated duration.
          </div>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 500, margin: '0 0 8px', color: 'var(--fg-0)' }}>4. Fair use</h3>
            We reserve the right to suspend accounts that show patterns consistent with abuse, including
            but not limited to credential stuffing, CSAM distribution, or attacks on our own or partner
            infrastructure.
          </div>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 500, margin: '0 0 8px', color: 'var(--fg-0)' }}>5. Liability</h3>
            The service is provided "as is." We target 99.9% monthly uptime but do not guarantee it. Our
            aggregate liability is limited to fees paid in the 30 days preceding the claim.
          </div>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 500, margin: '0 0 8px', color: 'var(--fg-0)' }}>6. Changes</h3>
            We may update these terms. Continued use after an update constitutes acceptance. Material changes
            will be announced at least 14 days in advance via email.
          </div>
          <div style={{ fontSize: 13, color: 'var(--fg-3)', paddingTop: 8 }}>
            Questions? <a href="#contact" style={{ color: 'var(--accent)' }}>Contact us →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

window.Landing = Landing;
window.PLANS = PLANS;
