/* global React, window */
/* ============================================
   VpsPage — recommended VPS providers for running
   Expert Advisors 24/7. Mirrors the brokers board.
   Admin can edit everything via the VPS editor.
   ============================================ */

function VpsLogo({ vps, size = 44 }) {
  const color = vps.color || 'var(--cyan)';
  if (vps.logoUrl) {
    return (
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, height: size }}>
        <img src={vps.logoUrl} alt={vps.name}
          style={{ maxHeight: size, maxWidth: 130, objectFit: 'contain', display: 'block', flexShrink: 0 }}/>
        <span className="broker-wordmark" style={{
          fontFamily: 'var(--font-display)', fontWeight: 800,
          letterSpacing: '-0.015em', color: 'var(--text)', whiteSpace: 'nowrap', lineHeight: 1,
        }}>{vps.name}</span>
      </div>
    );
  }
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 11, height: size }}>
      <span style={{
        width: size * 0.78, height: size * 0.78, borderRadius: 11, flexShrink: 0,
        display: 'grid', placeItems: 'center', background: `${color}1a`, border: `1px solid ${color}66`,
      }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="2" y="3" width="20" height="6" rx="1.5"/><rect x="2" y="13" width="20" height="6" rx="1.5"/>
          <path d="M6 6h.01M6 16h.01"/>
        </svg>
      </span>
      <span className="broker-wordmark" style={{
        fontFamily: 'var(--font-display)', fontWeight: 800,
        letterSpacing: '-0.015em', color: 'var(--text)', whiteSpace: 'nowrap', lineHeight: 1,
      }}>{vps.name}</span>
    </div>
  );
}

function VpsCard({ vps }) {
  const color = vps.color || 'var(--cyan)';
  const specs = [
    { label: 'PRICE', value: vps.price, accent: 'var(--green)' },
    { label: 'LATENCY', value: vps.latency, accent: 'var(--cyan)' },
    { label: 'UPTIME', value: vps.uptime, accent: 'var(--amber)' },
  ];
  const openSignup = () => { if (vps.signupUrl) window.open(vps.signupUrl, '_blank', 'noopener'); };
  return (
    <div className="panel panel-padded-lg lift broker-card" style={{
      position: 'relative', overflow: 'hidden', borderColor: 'var(--line)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: `linear-gradient(90deg, ${color}, transparent)` }}/>
      {vps.featured && (
        <span className="font-mono" style={{
          position: 'absolute', top: 16, right: 16, fontSize: 9, letterSpacing: '0.12em',
          color: '#0b0e14', background: color, padding: '3px 8px', borderRadius: 5, fontWeight: 700,
        }}>TOP PICK</span>
      )}

      <VpsLogo vps={vps} size={44} />
      <p className="text-muted text-sm mt-4" style={{ minHeight: 38 }}>{vps.tagline}</p>

      <div className="broker-spec-grid mt-5">
        {specs.map(s => (
          <div key={s.label} style={{
            background: 'rgba(0,0,0,0.28)', border: '1px solid var(--line-soft)',
            borderRadius: 10, padding: '12px 12px',
          }}>
            <div className="font-mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', color: 'var(--text-3)' }}>{s.label}</div>
            <div style={{ fontWeight: 700, fontSize: 16, marginTop: 6, color: s.accent }}>{s.value || '—'}</div>
          </div>
        ))}
      </div>

      {vps.locations && (
        <div className="mt-4">
          <div className="font-mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', color: 'var(--text-3)', marginBottom: 8 }}>SERVER LOCATIONS</div>
          <div className="flex" style={{ flexWrap: 'wrap', gap: 6 }}>
            {String(vps.locations || '').split('·').map(a => a.trim()).filter(Boolean).map((a, i) => (
              <span key={i} className="font-mono" style={{
                fontSize: 10.5, padding: '4px 9px', borderRadius: 6,
                background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line-soft)', color: 'var(--text-2)',
              }}>{a}</span>
            ))}
          </div>
        </div>
      )}

      {vps.perks && (
        <div className="mt-4 flex-col gap-2">
          {String(vps.perks || '').split('·').map(p => p.trim()).filter(Boolean).map((p, i) => (
            <div key={i} className="flex gap-2" style={{ alignItems: 'center' }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M20 6L9 17l-5-5"/></svg>
              <span className="text-xs text-muted">{p}</span>
            </div>
          ))}
        </div>
      )}

      <div style={{ flex: 1 }}/>
      <button onClick={openSignup} disabled={!vps.signupUrl} className="btn btn-lg btn-block mt-5"
        style={{
          background: vps.signupUrl ? color : 'rgba(255,255,255,0.05)',
          color: vps.signupUrl ? '#0b0e14' : 'var(--text-3)',
          fontWeight: 700, border: 'none', cursor: vps.signupUrl ? 'pointer' : 'not-allowed',
          boxShadow: vps.signupUrl ? `0 0 20px ${color}44` : 'none',
        }}>
        {vps.signupUrl ? 'Get started →' : 'Link coming soon'}
      </button>
    </div>
  );
}

function VpsPage({ go }) {
  const [, setTick] = React.useState(0);
  const [adminOn, setAdminOn] = React.useState(!!window.__effAdminMode);
  const [editorOpen, setEditorOpen] = React.useState(false);

  React.useEffect(() => {
    const onChange = () => setTick(t => t + 1);
    const onAdmin = () => setAdminOn(!!window.__effAdminMode);
    window.addEventListener('eff_vps_changed', onChange);
    window.addEventListener('eff_admin_changed', onAdmin);
    return () => {
      window.removeEventListener('eff_vps_changed', onChange);
      window.removeEventListener('eff_admin_changed', onAdmin);
    };
  }, []);

  const list = window.VpsStore?.getVps?.() || [];
  const intro = window.VpsStore?.getIntro?.() || '';

  return (
    <div>
      <section style={{ padding: '64px 0 28px' }}>
        <div className="container">
          <div className="flex" style={{ justifyContent: 'space-between', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
            <div style={{ maxWidth: 720 }}>
              <span className="eyebrow">INFRASTRUCTURE · VPS</span>
              <h1 className="mt-4" style={{ fontSize: 60, lineHeight: 1.02 }}>
                Recommended <span className="gradient-text">VPS</span>
              </h1>
              <p className="mt-6 text-muted" style={{ fontSize: 17, lineHeight: 1.6 }}>{intro}</p>
            </div>
            {adminOn && (
              <button className="btn btn-primary" onClick={() => setEditorOpen(true)}>⚙ Edit VPS</button>
            )}
          </div>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 12 }}>
        <div className="container">
          <div className="brokers-grid" style={{ display: 'grid', gap: 20, alignItems: 'stretch' }}>
            {list.map(v => <VpsCard key={v.id} vps={v} />)}
          </div>

          {list.length === 0 && (
            <div className="panel panel-padded-lg text-center text-muted">No VPS providers configured yet.</div>
          )}

          <p className="text-xs text-muted mt-8" style={{ maxWidth: 760, lineHeight: 1.6 }}>
            The providers above are independent companies; we may receive a partner commission when you sign up through our links, at no extra cost to you.
          </p>
        </div>
      </section>

      {editorOpen && window.VpsEditor && (
        <VpsEditor onClose={() => setEditorOpen(false)} />
      )}
    </div>
  );
}

window.VpsPage = VpsPage;
