// MCP Hero — marketplace: home (3 layout directions), MCP detail, pricing
const { useState: useMktState, useMemo: useMktMemo } = React;

// ---------- shared bits ----------
function MktSearch({ q, setQ, style = {} }) {
  const [focus, setFocus] = useMktState(false);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', borderRadius: 13,
      border: `1.5px solid ${focus ? 'var(--accent)' : 'var(--border-strong)'}`, background: 'var(--bg-raised)',
      boxShadow: focus ? '0 0 0 3px color-mix(in oklch, var(--accent) 16%, transparent)' : 'var(--shadow-sm)',
      transition: 'all .15s ease', ...style,
    }}>
      <Icon name="search" size={17} style={{ color: 'var(--text-3)' }}></Icon>
      <input
        value={q} onChange={(e) => setQ(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        placeholder="Search MCPs — company data, legal, tax…"
        style={{ border: 'none', outline: 'none', background: 'transparent', fontSize: 15, flex: 1, color: 'var(--text)' }}
      ></input>
      {q ? <button onClick={() => setQ('')} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--text-3)', padding: 2 }}><Icon name="close" size={15}></Icon></button> : null}
    </div>
  );
}

function CatChips({ cat, setCat }) {
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      {MH_CATEGORIES.map((c) => {
        const active = cat === c.id;
        return (
          <button key={c.id} onClick={() => setCat(c.id)} style={{
            padding: '7px 15px', borderRadius: 999, fontSize: 13.5, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
            border: `1.5px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
            background: active ? 'var(--accent)' : 'var(--bg-raised)',
            color: active ? 'var(--accent-contrast)' : 'var(--text-2)',
            transition: 'all .15s ease',
          }}>{c.label}</button>
        );
      })}
    </div>
  );
}

function useMktFilter() {
  const [q, setQ] = useMktState('');
  const [cat, setCat] = useMktState('all');
  const list = useMktMemo(() => {
    return MH_MCPS.filter((m) => m.status === 'active')
      .filter((m) => cat === 'all' || m.category === cat)
      .filter((m) => !q || q.length < 2 || (m.name + ' ' + m.tagline + ' ' + m.description).toLowerCase().includes(q.toLowerCase()));
  }, [q, cat]);
  return { q, setQ, cat, setCat, list };
}

function NoResults({ q }) {
  return <EmptyState icon="search" title="No MCPs found" sub={`Nothing matches “${q}”. Try a different keyword or browse by category.`}></EmptyState>;
}

// ---------- Direction A: Classic grid ----------
function McpCardA({ mcp, nav }) {
  return (
    <Card hoverable onClick={() => nav('/mcps/' + mcp.slug)} style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
        <McpIcon mcp={mcp} size={46}></McpIcon>
        <CategoryTag cat={mcp.category}></CategoryTag>
      </div>
      <div>
        <div style={{ fontWeight: 700, fontSize: 16.5, fontFamily: 'var(--font-display)', letterSpacing: '-.01em' }}>{mcp.name}</div>
        <p style={{ margin: '4px 0 0', fontSize: 13.5, color: 'var(--text-2)', lineHeight: 1.5 }}>{mcp.tagline}</p>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto', paddingTop: 4 }}>
        <CreditPill mcp={mcp}></CreditPill>
        <span style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <Icon name="download" size={13}></Icon>{mcp.installs.toLocaleString()}
        </span>
      </div>
    </Card>
  );
}

function HomeClassic({ nav }) {
  const { q, setQ, cat, setCat, list } = useMktFilter();
  return (
    <div className="mh-anim" style={{ maxWidth: 1080, margin: '0 auto', padding: '40px 28px 80px' }}>
      <div style={{ textAlign: 'center', maxWidth: 620, margin: '0 auto 32px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 40, fontWeight: 800, letterSpacing: '-.02em', margin: '20px 0 10px', lineHeight: 1.1 }}>
          Give your AI agent <span style={{ color: 'var(--accent)' }}>real Malaysian data</span>
        </h1>
        <p style={{ fontSize: 16, color: 'var(--text-2)', margin: '0 0 26px', lineHeight: 1.55 }}>
          Install production-ready MCPs into Claude Desktop or any MCP client. One gateway URL, one API key — pay only for what you call.
        </p>
        <MktSearch q={q} setQ={setQ} style={{ maxWidth: 540, margin: '0 auto' }}></MktSearch>
      </div>
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 28 }}>
        <CatChips cat={cat} setCat={setCat}></CatChips>
      </div>
      {list.length === 0 ? <NoResults q={q}></NoResults> : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 18 }}>
          {list.map((m) => <McpCardA key={m.slug} mcp={m} nav={nav}></McpCardA>)}
        </div>
      )}
    </div>
  );
}

// ---------- Direction B: Editorial / featured ----------
function HomeEditorial({ nav }) {
  const { q, setQ, cat, setCat, list } = useMktFilter();
  const featured = list.find((m) => m.featured);
  const rest = list.filter((m) => m !== featured);
  return (
    <div className="mh-anim" style={{ maxWidth: 1120, margin: '0 auto', padding: '36px 28px 80px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap', marginBottom: 26 }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 52, fontWeight: 800, letterSpacing: '-.03em', margin: 0, lineHeight: 1.02, maxWidth: 560 }}>
          The MCP marketplace for <em style={{ fontStyle: 'normal', color: 'var(--accent)' }}>Malaysian business.</em>
        </h1>
        <div style={{ flex: '0 1 380px', minWidth: 280 }}>
          <p style={{ fontSize: 14.5, color: 'var(--text-2)', margin: '0 0 14px', lineHeight: 1.55 }}>
            Official registries, courts, tax and more — wired into your AI client through one gateway.
          </p>
          <MktSearch q={q} setQ={setQ}></MktSearch>
        </div>
      </div>
      <div style={{ marginBottom: 22 }}><CatChips cat={cat} setCat={setCat}></CatChips></div>
      {featured ? (
        <Card hoverable onClick={() => nav('/mcps/' + featured.slug)} style={{
          padding: 0, marginBottom: 22, overflow: 'hidden',
          background: 'linear-gradient(120deg, color-mix(in oklch, var(--accent) 14%, var(--surface)), var(--surface) 60%)',
        }}>
          <div style={{ display: 'flex', gap: 28, padding: '30px 32px', alignItems: 'center', flexWrap: 'wrap' }}>
            <McpIcon mcp={featured} size={76}></McpIcon>
            <div style={{ flex: 1, minWidth: 260 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <Badge tone="accent"><Icon name="sparkle" size={12}></Icon>Featured</Badge>
                <CategoryTag cat={featured.category}></CategoryTag>
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 800, letterSpacing: '-.015em' }}>{featured.name}</div>
              <p style={{ margin: '5px 0 0', color: 'var(--text-2)', fontSize: 14.5, maxWidth: 520 }}>{featured.tagline}</p>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
              <CreditPill mcp={featured} size={13.5}></CreditPill>
              <Btn icon="arrowRight">View MCP</Btn>
            </div>
          </div>
        </Card>
      ) : null}
      {rest.length === 0 && !featured ? <NoResults q={q}></NoResults> : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 16 }}>
          {rest.map((m) => <McpCardA key={m.slug} mcp={m} nav={nav}></McpCardA>)}
        </div>
      )}
    </div>
  );
}

// ---------- Direction C: Dense directory ----------
function HomeDirectory({ nav }) {
  const { q, setQ, cat, setCat, list } = useMktFilter();
  return (
    <div className="mh-anim" style={{ maxWidth: 1120, margin: '0 auto', padding: '32px 28px 80px', display: 'flex', gap: 28, alignItems: 'flex-start' }}>
      <div style={{ width: 220, flexShrink: 0, position: 'sticky', top: 92, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em', color: 'var(--text-3)', padding: '4px 12px' }}>Categories</div>
        {MH_CATEGORIES.map((c) => {
          const active = cat === c.id;
          const n = c.id === 'all' ? MH_MCPS.filter((m) => m.status === 'active').length : MH_MCPS.filter((m) => m.status === 'active' && m.category === c.id).length;
          return (
            <button key={c.id} onClick={() => setCat(c.id)} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 12px',
              borderRadius: 9, border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 600, textAlign: 'left',
              background: active ? 'color-mix(in oklch, var(--accent) 11%, transparent)' : 'transparent',
              color: active ? 'var(--accent)' : 'var(--text-2)', transition: 'all .13s ease',
            }}>
              {c.label}
              <span style={{ fontSize: 12, color: active ? 'var(--accent)' : 'var(--text-3)' }}>{n}</span>
            </button>
          );
        })}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 800, letterSpacing: '-.015em', margin: '0 0 16px' }}>Browse MCPs</h1>
        <MktSearch q={q} setQ={setQ} style={{ marginBottom: 18 }}></MktSearch>
        {list.length === 0 ? <NoResults q={q}></NoResults> : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {list.map((m) => (
              <Card key={m.slug} hoverable onClick={() => nav('/mcps/' + m.slug)} style={{ padding: '16px 20px', display: 'flex', gap: 16, alignItems: 'center' }}>
                <McpIcon mcp={m} size={42}></McpIcon>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                    <span style={{ fontWeight: 700, fontSize: 15.5, fontFamily: 'var(--font-display)' }}>{m.name}</span>
                    <CategoryTag cat={m.category}></CategoryTag>
                  </div>
                  <p style={{ margin: '3px 0 0', fontSize: 13, color: 'var(--text-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.tagline}</p>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, flexShrink: 0 }}>
                  <CreditPill mcp={m}></CreditPill>
                  <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{m.installs.toLocaleString()} installs</span>
                </div>
                <Icon name="chevronRight" size={17} style={{ color: 'var(--text-3)' }}></Icon>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function MarketplaceHome({ nav, homeStyle }) {
  if (homeStyle === 'Editorial') return <HomeEditorial nav={nav}></HomeEditorial>;
  if (homeStyle === 'Directory') return <HomeDirectory nav={nav}></HomeDirectory>;
  return <HomeClassic nav={nav}></HomeClassic>;
}

// ---------- Install modal ----------
function InstallModal({ mcp, open, onClose, loggedIn, nav, balance }) {
  const [stage, setStage] = useMktState('confirm'); // confirm | done
  const toast = useToast();
  const key = 'mh_live_' + mcp.slug.replace(/-/g, '').slice(0, 4) + 'Xw9pQz7LmA2vRt4K';
  const lowCredits = !mcp.free && balance === 0;
  const close = () => { setStage('confirm'); onClose(); };
  if (!loggedIn) {
    return (
      <Modal open={open} onClose={close} title="Sign in to install">
        <p style={{ margin: '0 0 18px', color: 'var(--text-2)', fontSize: 14 }}>You need an account to install <strong>{mcp.name}</strong>. We'll bring you right back here.</p>
        <div style={{ display: 'flex', gap: 10 }}>
          <Btn onClick={() => nav('/login')} style={{ flex: 1, justifyContent: 'center' }}>Sign in</Btn>
          <Btn variant="secondary" onClick={() => nav('/register')} style={{ flex: 1, justifyContent: 'center' }}>Create account</Btn>
        </div>
      </Modal>
    );
  }
  return (
    <Modal open={open} onClose={close} title={stage === 'confirm' ? 'Install ' + mcp.name : 'Installed 🎉'} width={560}>
      {stage === 'confirm' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {lowCredits ? (
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '12px 14px', borderRadius: 11, background: 'var(--warn-bg)', color: 'var(--warn)', fontSize: 13.5 }}>
              <Icon name="alert" size={16} style={{ marginTop: 1 }}></Icon>
              <span><strong>You have 0 credits.</strong> You can still install — free tools work right away, but paid tools need a top-up. <a href="#" onClick={(e) => { e.preventDefault(); nav('/pricing'); }} style={{ color: 'inherit', fontWeight: 700 }}>Top up</a></span>
            </div>
          ) : null}
          <p style={{ margin: 0, color: 'var(--text-2)', fontSize: 14, lineHeight: 1.55 }}>
            Installing generates a <strong>unique API key</strong> scoped to your account and this MCP. You'll get a ready-to-paste config snippet for your AI client.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '14px 16px', borderRadius: 12, background: 'var(--bg-sunken)', fontSize: 13.5 }}>
            {mcp.tools.map((t) => (
              <div key={t.name} style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5, color: 'var(--text)' }}>{t.name}</code>
                <span style={{ fontWeight: 700, color: t.credits === 0 ? 'var(--ok)' : 'var(--text-2)', whiteSpace: 'nowrap' }}>{t.credits === 0 ? 'Free' : t.credits + ' cr'}</span>
              </div>
            ))}
          </div>
          <Btn size="lg" icon="zap" onClick={() => setStage('done')} style={{ justifyContent: 'center' }}>Install &amp; generate key</Btn>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <p style={{ margin: 0, color: 'var(--text-2)', fontSize: 14, lineHeight: 1.55 }}>
            Paste this into your <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5 }}>claude_desktop_config.json</code>, restart your client, and the tools appear in your AI session.
          </p>
          <CopyBlock code={mhConfigSnippet(mcp.slug, key)}></CopyBlock>
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '11px 14px', borderRadius: 11, background: 'var(--bg-sunken)', fontSize: 13, color: 'var(--text-2)' }}>
            <Icon name="shield" size={15} style={{ marginTop: 1, color: 'var(--text-3)' }}></Icon>
            <span>This is the only time the full key is shown. You can rotate it any time from your dashboard.</span>
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <Btn onClick={() => { close(); nav('/dashboard/mcps'); toast('Added to your installed MCPs'); }} style={{ flex: 1, justifyContent: 'center' }}>Go to my MCPs</Btn>
            <Btn variant="secondary" onClick={close}>Done</Btn>
          </div>
        </div>
      )}
    </Modal>
  );
}

// ---------- MCP detail ----------
function McpDetail({ slug, nav, loggedIn, balance }) {
  const mcp = mhGetMcp(slug) || MH_MCPS[0];
  const [installOpen, setInstallOpen] = useMktState(false);
  return (
    <div className="mh-anim" style={{ maxWidth: 980, margin: '0 auto', padding: '32px 28px 80px' }}>
      <button onClick={() => nav('/')} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--text-3)', fontSize: 13.5, fontWeight: 600, padding: 0, marginBottom: 22 }}>
        <Icon name="arrowLeft" size={15}></Icon> Marketplace
      </button>
      <div style={{ display: 'flex', gap: 24, alignItems: 'flex-start', flexWrap: 'wrap', marginBottom: 30 }}>
        <McpIcon mcp={mcp} size={72}></McpIcon>
        <div style={{ flex: 1, minWidth: 280 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, flexWrap: 'wrap' }}>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 800, letterSpacing: '-.02em', margin: 0 }}>{mcp.name}</h1>
            <CategoryTag cat={mcp.category} size={12.5}></CategoryTag>
          </div>
          <p style={{ margin: 0, fontSize: 15.5, color: 'var(--text-2)', maxWidth: 560, lineHeight: 1.55 }}>{mcp.description}</p>
          <div style={{ display: 'flex', gap: 18, marginTop: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <CreditPill mcp={mcp} size={13.5}></CreditPill>
            <span style={{ fontSize: 13, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Icon name="download" size={14}></Icon>{mcp.installs.toLocaleString()} installs
            </span>
            <span style={{ fontSize: 13, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Icon name="shield" size={14}></Icon>Managed by Agmo
            </span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          <Btn size="lg" icon="plus" onClick={() => setInstallOpen(true)}>Install MCP</Btn>
          <Btn variant="secondary" onClick={() => nav('/pricing')} style={{ justifyContent: 'center' }}>View pricing</Btn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.6fr) minmax(260px, 1fr)', gap: 22, alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <Card style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: 16 }}>Tools &amp; pricing</span>
              <span style={{ fontSize: 12.5, color: 'var(--text-3)' }}>{mcp.tools.length} tools</span>
            </div>
            {mcp.tools.map((t, i) => (
              <div key={t.name} style={{ display: 'flex', alignItems: 'flex-start', gap: 14, padding: '15px 22px', borderBottom: i < mcp.tools.length - 1 ? '1px solid var(--border)' : 'none' }}>
                <div style={{ flex: 1 }}>
                  <code style={{ fontFamily: 'var(--font-mono)', fontSize: 13.5, fontWeight: 600, color: 'var(--text)' }}>{t.name}</code>
                  <p style={{ margin: '3px 0 0', fontSize: 13, color: 'var(--text-2)' }}>{t.desc}</p>
                </div>
                <Badge tone={t.credits === 0 ? 'ok' : 'neutral'}>{t.credits === 0 ? 'Free' : t.credits + ' credits'}</Badge>
              </div>
            ))}
          </Card>
          <Card style={{ padding: 22 }}>
            <div style={{ fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: 16, marginBottom: 12 }}>Example use cases</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {mcp.useCases.map((u, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, fontSize: 13.5, color: 'var(--text-2)', lineHeight: 1.5 }}>
                  <Icon name="sparkle" size={14} style={{ color: 'var(--accent)', marginTop: 3 }}></Icon>{u}
                </div>
              ))}
            </div>
          </Card>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <Card style={{ padding: 22 }}>
            <div style={{ fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: 16, marginBottom: 10 }}>How installing works</div>
            <ol style={{ margin: 0, padding: '0 0 0 18px', display: 'flex', flexDirection: 'column', gap: 9, fontSize: 13.5, color: 'var(--text-2)', lineHeight: 1.5 }}>
              <li>Click <strong>Install</strong> — we generate an API key just for you and this MCP.</li>
              <li>Copy the config snippet into your MCP client.</li>
              <li>Restart the client. Tools appear in your AI session.</li>
              <li>Credits deduct per call — free tools never charge.</li>
            </ol>
          </Card>
          <Card style={{ padding: 22, background: 'color-mix(in oklch, var(--accent) 6%, var(--surface))' }}>
            <div style={{ fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: 16, marginBottom: 8 }}>Gateway endpoint</div>
            <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-2)', wordBreak: 'break-all', display: 'block', lineHeight: 1.6 }}>
              {MH_GATEWAY_URL}{mcp.slug}
            </code>
            <p style={{ margin: '10px 0 0', fontSize: 12.5, color: 'var(--text-3)', lineHeight: 1.5 }}>Auth, credit checks and logging happen at the gateway — the backend server never sees your key.</p>
          </Card>
        </div>
      </div>
      <InstallModal mcp={mcp} open={installOpen} onClose={() => setInstallOpen(false)} loggedIn={loggedIn} nav={nav} balance={balance}></InstallModal>
    </div>
  );
}

// ---------- Pricing ----------
function PricingPage({ nav, loggedIn, canTopUp, payState }) {
  const [selected, setSelected] = useMktState('standard');
  const toast = useToast();
  return (
    <div className="mh-anim" style={{ maxWidth: 1020, margin: '0 auto', padding: '44px 28px 80px' }}>
      <div style={{ textAlign: 'center', maxWidth: 560, margin: '0 auto 14px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 38, fontWeight: 800, letterSpacing: '-.02em', margin: '0 0 10px' }}>Simple credit pricing</h1>
        <p style={{ fontSize: 15.5, color: 'var(--text-2)', margin: 0, lineHeight: 1.55 }}>
          Buy credits once, spend them on any MCP. <strong>Credits never expire.</strong>
        </p>
      </div>
      {payState === 'failed' ? (
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', justifyContent: 'center', padding: '12px 18px', borderRadius: 12, background: 'var(--danger-bg)', color: 'var(--danger)', fontSize: 14, fontWeight: 600, maxWidth: 560, margin: '18px auto 0' }}>
          <Icon name="alert" size={16}></Icon> Payment unsuccessful — no credits were added. Your package is still selected, try again below.
        </div>
      ) : null}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 18, margin: '36px 0 26px' }}>
        {MH_PACKAGES.map((p) => {
          const active = selected === p.id;
          const custom = p.id === 'custom';
          return (
            <Card key={p.id} hoverable onClick={() => !custom && setSelected(p.id)} style={{
              padding: 24, position: 'relative', display: 'flex', flexDirection: 'column', gap: 6,
              border: `2px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
              background: active ? 'color-mix(in oklch, var(--accent) 6%, var(--surface))' : 'var(--surface)',
            }}>
              {p.popular ? (
                <span style={{ position: 'absolute', top: -11, left: '50%', transform: 'translateX(-50%)', padding: '3px 12px', borderRadius: 999, background: 'var(--accent)', color: 'var(--accent-contrast)', fontSize: 11.5, fontWeight: 700, letterSpacing: '.03em', whiteSpace: 'nowrap' }}>MOST POPULAR</span>
              ) : null}
              <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--text-2)' }}>{p.name}</div>
              {custom ? (
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 800, letterSpacing: '-.02em' }}>Let's talk</div>
              ) : (
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 800, letterSpacing: '-.02em' }}>RM {p.price}</span>
                </div>
              )}
              {!custom ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <Icon name="coin" size={15} style={{ color: 'var(--warn)' }}></Icon>
                  <span style={{ fontWeight: 700, fontSize: 15.5 }}>{p.credits.toLocaleString()} credits</span>
                  {p.bonus ? <Badge tone="ok">{p.bonus}</Badge> : null}
                </div>
              ) : null}
              <div style={{ fontSize: 12.5, color: 'var(--text-3)', marginTop: 2 }}>{p.note}</div>
              {custom ? <Btn variant="secondary" size="sm" style={{ marginTop: 10, alignSelf: 'flex-start' }} onClick={() => toast('We\u2019ll be in touch — sales@agmostudio.com')}>Contact sales</Btn> : null}
            </Card>
          );
        })}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
        {loggedIn && !canTopUp ? (
          <div style={{ display: 'flex', gap: 9, alignItems: 'center', padding: '11px 16px', borderRadius: 11, background: 'var(--bg-sunken)', fontSize: 13.5, color: 'var(--text-2)' }}>
            <Icon name="shield" size={15} style={{ color: 'var(--text-3)' }}></Icon>
            Only your <strong>Org Admin</strong> can top up the team credit pool.
          </div>
        ) : (
          <Btn size="lg" icon="zap" onClick={() => loggedIn ? toast('Redirecting to Stripe checkout…') : nav('/register')}>
            {loggedIn ? 'Top up ' + (MH_PACKAGES.find((p) => p.id === selected).credits.toLocaleString()) + ' credits' : 'Get started free'}
          </Btn>
        )}
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', fontSize: 12.5, color: 'var(--text-3)' }}>
          <span>Pay with</span>
          {['Stripe', 'iPay88', 'Razorpay'].map((g) => (
            <span key={g} style={{ padding: '3px 10px', borderRadius: 7, background: 'var(--bg-sunken)', fontWeight: 600, border: '1px solid var(--border)' }}>{g}</span>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MarketplaceHome, McpDetail, PricingPage, InstallModal, MktSearch, CatChips });
